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