]> git.lizzy.rs Git - rust.git/blob - src/driver/aot.rs
Rustup to rustc 1.44.0-nightly (1edd389cc 2020-03-23)
[rust.git] / src / driver / aot.rs
1 use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
2 use rustc::middle::cstore::EncodedMetadata;
3 use rustc::mir::mono::CodegenUnit;
4 use rustc_session::config::{DebugInfo, OutputType};
5 use rustc_session::cgu_reuse_tracker::CguReuse;
6 use rustc_codegen_ssa::back::linker::LinkerInfo;
7 use rustc_codegen_ssa::CrateInfo;
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9
10 use crate::prelude::*;
11
12 use crate::backend::{Emit, WriteDebugInfo};
13
14 fn new_module(tcx: TyCtxt<'_>, name: String) -> Module<crate::backend::Backend> {
15     let module = crate::backend::make_module(tcx.sess, name);
16     assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
17     module
18 }
19
20 struct ModuleCodegenResult(CompiledModule, Option<(WorkProductId, WorkProduct)>);
21
22
23 impl<HCX> HashStable<HCX> for ModuleCodegenResult {
24     fn hash_stable(&self, _: &mut HCX, _: &mut StableHasher) {
25         // do nothing
26     }
27 }
28
29 fn emit_module<B: Backend>(
30     tcx: TyCtxt<'_>,
31     name: String,
32     kind: ModuleKind,
33     mut module: Module<B>,
34     debug: Option<DebugContext>,
35 ) -> ModuleCodegenResult
36     where B::Product: Emit + WriteDebugInfo,
37 {
38     module.finalize_definitions();
39     let mut product = module.finish();
40
41     if let Some(mut debug) = debug {
42         debug.emit(&mut product);
43     }
44
45     let tmp_file = tcx
46         .output_filenames(LOCAL_CRATE)
47         .temp_path(OutputType::Object, Some(&name));
48     let obj = product.emit();
49     std::fs::write(&tmp_file, obj).unwrap();
50
51     let work_product = if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() {
52         None
53     } else {
54         rustc_incremental::copy_cgu_workproducts_to_incr_comp_cache_dir(
55             tcx.sess,
56             &name,
57             &[(WorkProductFileKind::Object, tmp_file.clone())],
58         )
59     };
60
61     ModuleCodegenResult(
62         CompiledModule {
63             name,
64             kind,
65             object: Some(tmp_file),
66             bytecode: None,
67             bytecode_compressed: None,
68         },
69         work_product,
70     )
71 }
72
73 fn reuse_workproduct_for_cgu(
74     tcx: TyCtxt<'_>,
75     cgu: &CodegenUnit,
76     work_products: &mut FxHashMap<WorkProductId, WorkProduct>,
77 ) -> CompiledModule {
78     let incr_comp_session_dir = tcx.sess.incr_comp_session_dir();
79     let mut object = None;
80     let work_product = cgu.work_product(tcx);
81     for (kind, saved_file) in &work_product.saved_files {
82         let obj_out = match kind {
83             WorkProductFileKind::Object => {
84                 let path = tcx.output_filenames(LOCAL_CRATE).temp_path(OutputType::Object, Some(&cgu.name().as_str()));
85                 object = Some(path.clone());
86                 path
87             }
88             WorkProductFileKind::Bytecode | WorkProductFileKind::BytecodeCompressed => {
89                 panic!("cg_clif doesn't use bytecode");
90             }
91         };
92         let source_file = rustc_incremental::in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
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
103     work_products.insert(cgu.work_product_id(), work_product);
104
105     CompiledModule {
106         name: cgu.name().to_string(),
107         kind: ModuleKind::Regular,
108         object,
109         bytecode: None,
110         bytecode_compressed: None,
111     }
112 }
113
114 fn module_codegen(tcx: TyCtxt<'_>, cgu_name: rustc_span::Symbol) -> ModuleCodegenResult {
115     let cgu = tcx.codegen_unit(cgu_name);
116     let mono_items = cgu.items_in_deterministic_order(tcx);
117
118     let mut module = new_module(tcx, cgu_name.as_str().to_string());
119
120     let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None {
121         let debug = DebugContext::new(
122             tcx,
123             module.target_config().pointer_type().bytes() as u8,
124         );
125         Some(debug)
126     } else {
127         None
128     };
129
130     super::codegen_mono_items(tcx, &mut module, debug.as_mut(), mono_items);
131     crate::main_shim::maybe_create_entry_wrapper(tcx, &mut module);
132
133     emit_module(
134         tcx,
135         cgu.name().as_str().to_string(),
136         ModuleKind::Regular,
137         module,
138         debug,
139     )
140 }
141
142 pub(super) fn run_aot(
143     tcx: TyCtxt<'_>,
144     metadata: EncodedMetadata,
145     need_metadata_module: bool,
146 ) -> Box<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)> {
147     let mut work_products = FxHashMap::default();
148
149     let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
150
151     if tcx.dep_graph.is_fully_enabled() {
152         for cgu in &*cgus {
153             tcx.codegen_unit(cgu.name());
154         }
155     }
156
157     let modules = super::time(tcx, "codegen mono items", || {
158         cgus.iter().map(|cgu| {
159             let cgu_reuse = determine_cgu_reuse(tcx, cgu);
160             tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
161
162             match cgu_reuse {
163                 _ if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() => {}
164                 CguReuse::No => {}
165                 CguReuse::PreLto => {
166                     return reuse_workproduct_for_cgu(tcx, &*cgu, &mut work_products);
167                 }
168                 CguReuse::PostLto => unreachable!(),
169             }
170
171             let dep_node = cgu.codegen_dep_node(tcx);
172             let (ModuleCodegenResult(module, work_product), _) =
173                 tcx.dep_graph.with_task(dep_node, tcx, cgu.name(), module_codegen, rustc::dep_graph::hash_result);
174
175             if let Some((id, product)) = work_product {
176                 work_products.insert(id, product);
177             }
178
179             module
180         }).collect::<Vec<_>>()
181     });
182
183     tcx.sess.abort_if_errors();
184
185     let mut allocator_module = new_module(tcx, "allocator_shim".to_string());
186     let created_alloc_shim = crate::allocator::codegen(tcx, &mut allocator_module);
187
188     let allocator_module = if created_alloc_shim {
189         let ModuleCodegenResult(module, work_product) = emit_module(
190             tcx,
191             "allocator_shim".to_string(),
192             ModuleKind::Allocator,
193             allocator_module,
194             None,
195         );
196         if let Some((id, product)) = work_product {
197             work_products.insert(id, product);
198         }
199         Some(module)
200     } else {
201         None
202     };
203
204     rustc_incremental::assert_dep_graph(tcx);
205     rustc_incremental::save_dep_graph(tcx);
206
207     let metadata_module = if need_metadata_module {
208         let _timer = tcx.prof.generic_activity("codegen crate metadata");
209         let (metadata_cgu_name, tmp_file) = tcx.sess.time("write compressed metadata", || {
210             use rustc::mir::mono::CodegenUnitNameBuilder;
211
212             let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
213             let metadata_cgu_name = cgu_name_builder
214                 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
215                 .as_str()
216                 .to_string();
217
218             let tmp_file = tcx
219                 .output_filenames(LOCAL_CRATE)
220                 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
221
222             let obj = crate::backend::with_object(tcx.sess, &metadata_cgu_name, |object| {
223                 crate::metadata::write_metadata(tcx, object);
224             });
225
226             std::fs::write(&tmp_file, obj).unwrap();
227
228             (metadata_cgu_name, tmp_file)
229         });
230
231         Some(CompiledModule {
232             name: metadata_cgu_name,
233             kind: ModuleKind::Metadata,
234             object: Some(tmp_file),
235             bytecode: None,
236             bytecode_compressed: None,
237         })
238     } else {
239         None
240     };
241
242     Box::new((CodegenResults {
243         crate_name: tcx.crate_name(LOCAL_CRATE),
244         modules,
245         allocator_module,
246         metadata_module,
247         crate_hash: tcx.crate_hash(LOCAL_CRATE),
248         metadata,
249         windows_subsystem: None, // Windows is not yet supported
250         linker_info: LinkerInfo::new(tcx),
251         crate_info: CrateInfo::new(tcx),
252     }, work_products))
253 }
254
255 // Adapted from https://github.com/rust-lang/rust/blob/303d8aff6092709edd4dbd35b1c88e9aa40bf6d8/src/librustc_codegen_ssa/base.rs#L922-L953
256 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
257     if !tcx.dep_graph.is_fully_enabled() {
258         return CguReuse::No;
259     }
260
261     let work_product_id = &cgu.work_product_id();
262     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
263         // We don't have anything cached for this CGU. This can happen
264         // if the CGU did not exist in the previous session.
265         return CguReuse::No;
266     }
267
268     // Try to mark the CGU as green. If it we can do so, it means that nothing
269     // affecting the LLVM module has changed and we can re-use a cached version.
270     // If we compile with any kind of LTO, this means we can re-use the bitcode
271     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
272     // know that later). If we are not doing LTO, there is only one optimized
273     // version of each module, so we re-use that.
274     let dep_node = cgu.codegen_dep_node(tcx);
275     assert!(
276         !tcx.dep_graph.dep_node_exists(&dep_node),
277         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
278         cgu.name()
279     );
280
281     if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
282         CguReuse::PreLto
283     } else {
284         CguReuse::No
285     }
286 }