1 //! The AOT driver uses [`cranelift_object`] to write object files suitable for linking into a
2 //! standalone executable.
4 use std::path::PathBuf;
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};
15 use cranelift_object::{ObjectModule, ObjectProduct};
17 use crate::prelude::*;
19 use crate::backend::AddConstructor;
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());
27 struct ModuleCodegenResult(CompiledModule, Option<(WorkProductId, WorkProduct)>);
29 impl<HCX> HashStable<HCX> for ModuleCodegenResult {
30 fn hash_stable(&self, _: &mut HCX, _: &mut StableHasher) {
40 debug: Option<DebugContext<'_>>,
41 unwind_context: UnwindContext<'_>,
42 map_product: impl FnOnce(ObjectProduct) -> ObjectProduct,
43 ) -> ModuleCodegenResult {
44 let mut product = module.finish();
46 if let Some(mut debug) = debug {
47 debug.emit(&mut product);
50 unwind_context.emit(&mut product);
52 let product = map_product(product);
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) {
60 .fatal(&format!("error writing object file: {}", err));
63 let work_product = if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() {
66 rustc_incremental::copy_cgu_workproduct_to_incr_comp_cache_dir(
69 &Some(tmp_file.clone()),
77 object: Some(tmp_file),
85 fn reuse_workproduct_for_cgu(
87 cgu: &CodegenUnit<'_>,
88 work_products: &mut FxHashMap<WorkProductId, WorkProduct>,
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 {
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(),
109 work_products.insert(cgu.work_product_id(), work_product);
112 name: cgu.name().to_string(),
113 kind: ModuleKind::Regular,
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);
124 let mut module = new_module(tcx, cgu_name.as_str().to_string());
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;
132 .contains(&rustc_session::config::CrateType::ProcMacro)
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))
138 .contains("__rustc_proc_macro_decls_"),
141 init_atomics_mutex_from_constructor =
142 Some(crate::atomic_shim::init_global_lock_constructor(
144 &format!("{}_init_atomics_mutex", cgu_name.as_str()),
149 let mut cx = crate::CodegenCx::new(
152 tcx.sess.opts.debuginfo != DebugInfo::None,
155 super::predefine_mono_items(&mut cx, &mono_items);
156 for (mono_item, (linkage, visibility)) in mono_items {
157 let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
159 MonoItem::Fn(inst) => {
160 cx.tcx.sess.time("codegen fn", || {
161 crate::base::codegen_fn(&mut cx, inst, linkage)
164 MonoItem::Static(def_id) => {
165 crate::constant::codegen_static(&mut cx.constants_cx, def_id)
167 MonoItem::GlobalAsm(hir_id) => {
168 let item = cx.tcx.hir().expect_item(hir_id);
169 if let rustc_hir::ItemKind::GlobalAsm(rustc_hir::GlobalAsm { asm }) = item.kind {
170 cx.global_asm.push_str(&*asm.as_str());
171 cx.global_asm.push_str("\n\n");
173 bug!("Expected GlobalAsm found {:?}", item);
178 let (mut module, global_asm, debug, mut unwind_context) =
179 tcx.sess.time("finalize CodegenCx", || cx.finalize());
180 crate::main_shim::maybe_create_entry_wrapper(tcx, &mut module, &mut unwind_context, false);
182 let codegen_result = emit_module(
184 cgu.name().as_str().to_string(),
190 if let Some(func_id) = init_atomics_mutex_from_constructor {
191 product.add_constructor(func_id);
198 codegen_global_asm(tcx, &cgu.name().as_str(), &global_asm);
203 pub(super) fn run_aot(
205 metadata: EncodedMetadata,
206 need_metadata_module: bool,
207 ) -> Box<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)> {
208 let mut work_products = FxHashMap::default();
210 let cgus = if tcx.sess.opts.output_types.should_codegen() {
211 tcx.collect_and_partition_mono_items(LOCAL_CRATE).1
213 // If only `--emit metadata` is used, we shouldn't perform any codegen.
214 // Also `tcx.collect_and_partition_mono_items` may panic in that case.
218 if tcx.dep_graph.is_fully_enabled() {
220 tcx.ensure().codegen_unit(cgu.name());
224 let modules = super::time(tcx, "codegen mono items", || {
227 let cgu_reuse = determine_cgu_reuse(tcx, cgu);
230 .set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
233 _ if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() => {}
235 CguReuse::PreLto => {
236 return reuse_workproduct_for_cgu(tcx, &*cgu, &mut work_products);
238 CguReuse::PostLto => unreachable!(),
241 let dep_node = cgu.codegen_dep_node(tcx);
242 let (ModuleCodegenResult(module, work_product), _) = tcx.dep_graph.with_task(
247 rustc_middle::dep_graph::hash_result,
250 if let Some((id, product)) = work_product {
251 work_products.insert(id, product);
259 tcx.sess.abort_if_errors();
261 let mut allocator_module = new_module(tcx, "allocator_shim".to_string());
262 let mut allocator_unwind_context = UnwindContext::new(tcx, allocator_module.isa(), true);
263 let created_alloc_shim =
264 crate::allocator::codegen(tcx, &mut allocator_module, &mut allocator_unwind_context);
266 let allocator_module = if created_alloc_shim {
267 let ModuleCodegenResult(module, work_product) = emit_module(
269 "allocator_shim".to_string(),
270 ModuleKind::Allocator,
273 allocator_unwind_context,
276 if let Some((id, product)) = work_product {
277 work_products.insert(id, product);
284 rustc_incremental::assert_dep_graph(tcx);
285 rustc_incremental::save_dep_graph(tcx);
287 let metadata_module = if need_metadata_module {
288 let _timer = tcx.prof.generic_activity("codegen crate metadata");
289 let (metadata_cgu_name, tmp_file) = tcx.sess.time("write compressed metadata", || {
290 use rustc_middle::mir::mono::CodegenUnitNameBuilder;
292 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
293 let metadata_cgu_name = cgu_name_builder
294 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
299 .output_filenames(LOCAL_CRATE)
300 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
302 let obj = crate::backend::with_object(tcx.sess, &metadata_cgu_name, |object| {
303 crate::metadata::write_metadata(tcx, object);
306 if let Err(err) = std::fs::write(&tmp_file, obj) {
308 .fatal(&format!("error writing metadata object file: {}", err));
311 (metadata_cgu_name, tmp_file)
314 Some(CompiledModule {
315 name: metadata_cgu_name,
316 kind: ModuleKind::Metadata,
317 object: Some(tmp_file),
325 if tcx.sess.opts.output_types.should_codegen() {
326 rustc_incremental::assert_module_sources::assert_module_sources(tcx);
331 crate_name: tcx.crate_name(LOCAL_CRATE),
336 windows_subsystem: None, // Windows is not yet supported
337 linker_info: LinkerInfo::new(tcx),
338 crate_info: CrateInfo::new(tcx),
344 fn codegen_global_asm(tcx: TyCtxt<'_>, cgu_name: &str, global_asm: &str) {
346 use std::process::{Command, Stdio};
348 if global_asm.is_empty() {
352 if cfg!(not(feature = "inline_asm"))
353 || tcx.sess.target.is_like_osx
354 || tcx.sess.target.is_like_windows
356 if global_asm.contains("__rust_probestack") {
360 // FIXME fix linker error on macOS
361 if cfg!(not(feature = "inline_asm")) {
363 "asm! and global_asm! support is disabled while compiling rustc_codegen_cranelift",
367 .fatal("asm! and global_asm! are not yet supported on macOS and Windows");
371 let assembler = crate::toolchain::get_toolchain_binary(tcx.sess, "as");
372 let linker = crate::toolchain::get_toolchain_binary(tcx.sess, "ld");
374 // Remove all LLVM style comments
375 let global_asm = global_asm
378 if let Some(index) = line.find("//") {
387 let output_object_file = tcx
388 .output_filenames(LOCAL_CRATE)
389 .temp_path(OutputType::Object, Some(cgu_name));
391 // Assemble `global_asm`
392 let global_asm_object_file = add_file_stem_postfix(output_object_file.clone(), ".asm");
393 let mut child = Command::new(assembler)
395 .arg(&global_asm_object_file)
396 .stdin(Stdio::piped())
398 .expect("Failed to spawn `as`.");
403 .write_all(global_asm.as_bytes())
405 let status = child.wait().expect("Failed to wait for `as`.");
406 if !status.success() {
408 .fatal(&format!("Failed to assemble `{}`", global_asm));
411 // Link the global asm and main object file together
412 let main_object_file = add_file_stem_postfix(output_object_file.clone(), ".main");
413 std::fs::rename(&output_object_file, &main_object_file).unwrap();
414 let status = Command::new(linker)
415 .arg("-r") // Create a new object file
417 .arg(output_object_file)
418 .arg(&main_object_file)
419 .arg(&global_asm_object_file)
422 if !status.success() {
423 tcx.sess.fatal(&format!(
424 "Failed to link `{}` and `{}` together",
425 main_object_file.display(),
426 global_asm_object_file.display(),
430 std::fs::remove_file(global_asm_object_file).unwrap();
431 std::fs::remove_file(main_object_file).unwrap();
434 fn add_file_stem_postfix(mut path: PathBuf, postfix: &str) -> PathBuf {
435 let mut new_filename = path.file_stem().unwrap().to_owned();
436 new_filename.push(postfix);
437 if let Some(extension) = path.extension() {
438 new_filename.push(".");
439 new_filename.push(extension);
441 path.set_file_name(new_filename);
445 // Adapted from https://github.com/rust-lang/rust/blob/303d8aff6092709edd4dbd35b1c88e9aa40bf6d8/src/librustc_codegen_ssa/base.rs#L922-L953
446 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
447 if !tcx.dep_graph.is_fully_enabled() {
451 let work_product_id = &cgu.work_product_id();
454 .previous_work_product(work_product_id)
457 // We don't have anything cached for this CGU. This can happen
458 // if the CGU did not exist in the previous session.
462 // Try to mark the CGU as green. If it we can do so, it means that nothing
463 // affecting the LLVM module has changed and we can re-use a cached version.
464 // If we compile with any kind of LTO, this means we can re-use the bitcode
465 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
466 // know that later). If we are not doing LTO, there is only one optimized
467 // version of each module, so we re-use that.
468 let dep_node = cgu.codegen_dep_node(tcx);
470 !tcx.dep_graph.dep_node_exists(&dep_node),
471 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
475 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {