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