]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir/src/monomorphize/partitioning/default.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_mir / src / monomorphize / partitioning / default.rs
CommitLineData
3dfed10e
XL
1use std::collections::hash_map::Entry;
2
3use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4use rustc_hir::def::DefKind;
5use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
1b1a35ee 6use rustc_hir::definitions::DefPathDataName;
3dfed10e
XL
7use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8use rustc_middle::middle::exported_symbols::SymbolExportLevel;
9use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, Linkage, Visibility};
10use rustc_middle::mir::mono::{InstantiationMode, MonoItem};
11use rustc_middle::ty::print::characteristic_def_id_of_type;
12use rustc_middle::ty::{self, DefIdTree, InstanceDef, TyCtxt};
13use rustc_span::symbol::Symbol;
14
1b1a35ee 15use super::PartitioningCx;
3dfed10e
XL
16use crate::monomorphize::collector::InliningMap;
17use crate::monomorphize::partitioning::merging;
18use crate::monomorphize::partitioning::{
19 MonoItemPlacement, Partitioner, PostInliningPartitioning, PreInliningPartitioning,
20};
21
22pub struct DefaultPartitioning;
23
24impl<'tcx> Partitioner<'tcx> for DefaultPartitioning {
25 fn place_root_mono_items(
26 &mut self,
1b1a35ee 27 cx: &PartitioningCx<'_, 'tcx>,
3dfed10e
XL
28 mono_items: &mut dyn Iterator<Item = MonoItem<'tcx>>,
29 ) -> PreInliningPartitioning<'tcx> {
30 let mut roots = FxHashSet::default();
31 let mut codegen_units = FxHashMap::default();
1b1a35ee 32 let is_incremental_build = cx.tcx.sess.opts.incremental.is_some();
3dfed10e
XL
33 let mut internalization_candidates = FxHashSet::default();
34
35 // Determine if monomorphizations instantiated in this crate will be made
36 // available to downstream crates. This depends on whether we are in
37 // share-generics mode and whether the current crate can even have
38 // downstream crates.
1b1a35ee
XL
39 let export_generics =
40 cx.tcx.sess.opts.share_generics() && cx.tcx.local_crate_exports_generics();
3dfed10e 41
1b1a35ee 42 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
3dfed10e
XL
43 let cgu_name_cache = &mut FxHashMap::default();
44
45 for mono_item in mono_items {
1b1a35ee 46 match mono_item.instantiation_mode(cx.tcx) {
3dfed10e
XL
47 InstantiationMode::GloballyShared { .. } => {}
48 InstantiationMode::LocalCopy => continue,
49 }
50
1b1a35ee 51 let characteristic_def_id = characteristic_def_id_of_mono_item(cx.tcx, mono_item);
3dfed10e
XL
52 let is_volatile = is_incremental_build && mono_item.is_generic_fn();
53
54 let codegen_unit_name = match characteristic_def_id {
55 Some(def_id) => compute_codegen_unit_name(
1b1a35ee 56 cx.tcx,
3dfed10e
XL
57 cgu_name_builder,
58 def_id,
59 is_volatile,
60 cgu_name_cache,
61 ),
62 None => fallback_cgu_name(cgu_name_builder),
63 };
64
65 let codegen_unit = codegen_units
66 .entry(codegen_unit_name)
67 .or_insert_with(|| CodegenUnit::new(codegen_unit_name));
68
69 let mut can_be_internalized = true;
70 let (linkage, visibility) = mono_item_linkage_and_visibility(
1b1a35ee 71 cx.tcx,
3dfed10e
XL
72 &mono_item,
73 &mut can_be_internalized,
74 export_generics,
75 );
76 if visibility == Visibility::Hidden && can_be_internalized {
77 internalization_candidates.insert(mono_item);
78 }
79
80 codegen_unit.items_mut().insert(mono_item, (linkage, visibility));
81 roots.insert(mono_item);
82 }
83
84 // Always ensure we have at least one CGU; otherwise, if we have a
85 // crate with just types (for example), we could wind up with no CGU.
86 if codegen_units.is_empty() {
87 let codegen_unit_name = fallback_cgu_name(cgu_name_builder);
88 codegen_units.insert(codegen_unit_name, CodegenUnit::new(codegen_unit_name));
89 }
90
91 PreInliningPartitioning {
92 codegen_units: codegen_units
93 .into_iter()
94 .map(|(_, codegen_unit)| codegen_unit)
95 .collect(),
96 roots,
97 internalization_candidates,
98 }
99 }
100
101 fn merge_codegen_units(
102 &mut self,
1b1a35ee 103 cx: &PartitioningCx<'_, 'tcx>,
3dfed10e 104 initial_partitioning: &mut PreInliningPartitioning<'tcx>,
3dfed10e 105 ) {
1b1a35ee 106 merging::merge_codegen_units(cx, initial_partitioning);
3dfed10e
XL
107 }
108
109 fn place_inlined_mono_items(
110 &mut self,
1b1a35ee 111 cx: &PartitioningCx<'_, 'tcx>,
3dfed10e 112 initial_partitioning: PreInliningPartitioning<'tcx>,
3dfed10e
XL
113 ) -> PostInliningPartitioning<'tcx> {
114 let mut new_partitioning = Vec::new();
115 let mut mono_item_placements = FxHashMap::default();
116
117 let PreInliningPartitioning {
118 codegen_units: initial_cgus,
119 roots,
120 internalization_candidates,
121 } = initial_partitioning;
122
123 let single_codegen_unit = initial_cgus.len() == 1;
124
125 for old_codegen_unit in initial_cgus {
126 // Collect all items that need to be available in this codegen unit.
127 let mut reachable = FxHashSet::default();
128 for root in old_codegen_unit.items().keys() {
1b1a35ee 129 follow_inlining(*root, cx.inlining_map, &mut reachable);
3dfed10e
XL
130 }
131
132 let mut new_codegen_unit = CodegenUnit::new(old_codegen_unit.name());
133
134 // Add all monomorphizations that are not already there.
135 for mono_item in reachable {
136 if let Some(linkage) = old_codegen_unit.items().get(&mono_item) {
137 // This is a root, just copy it over.
138 new_codegen_unit.items_mut().insert(mono_item, *linkage);
139 } else {
140 if roots.contains(&mono_item) {
141 bug!(
142 "GloballyShared mono-item inlined into other CGU: \
143 {:?}",
144 mono_item
145 );
146 }
147
148 // This is a CGU-private copy.
149 new_codegen_unit
150 .items_mut()
151 .insert(mono_item, (Linkage::Internal, Visibility::Default));
152 }
153
154 if !single_codegen_unit {
155 // If there is more than one codegen unit, we need to keep track
156 // in which codegen units each monomorphization is placed.
157 match mono_item_placements.entry(mono_item) {
158 Entry::Occupied(e) => {
159 let placement = e.into_mut();
160 debug_assert!(match *placement {
161 MonoItemPlacement::SingleCgu { cgu_name } => {
162 cgu_name != new_codegen_unit.name()
163 }
164 MonoItemPlacement::MultipleCgus => true,
165 });
166 *placement = MonoItemPlacement::MultipleCgus;
167 }
168 Entry::Vacant(e) => {
169 e.insert(MonoItemPlacement::SingleCgu {
170 cgu_name: new_codegen_unit.name(),
171 });
172 }
173 }
174 }
175 }
176
177 new_partitioning.push(new_codegen_unit);
178 }
179
180 return PostInliningPartitioning {
181 codegen_units: new_partitioning,
182 mono_item_placements,
183 internalization_candidates,
184 };
185
186 fn follow_inlining<'tcx>(
187 mono_item: MonoItem<'tcx>,
188 inlining_map: &InliningMap<'tcx>,
189 visited: &mut FxHashSet<MonoItem<'tcx>>,
190 ) {
191 if !visited.insert(mono_item) {
192 return;
193 }
194
195 inlining_map.with_inlining_candidates(mono_item, |target| {
196 follow_inlining(target, inlining_map, visited);
197 });
198 }
199 }
200
201 fn internalize_symbols(
202 &mut self,
1b1a35ee 203 cx: &PartitioningCx<'_, 'tcx>,
3dfed10e 204 partitioning: &mut PostInliningPartitioning<'tcx>,
3dfed10e
XL
205 ) {
206 if partitioning.codegen_units.len() == 1 {
207 // Fast path for when there is only one codegen unit. In this case we
208 // can internalize all candidates, since there is nowhere else they
209 // could be accessed from.
210 for cgu in &mut partitioning.codegen_units {
211 for candidate in &partitioning.internalization_candidates {
212 cgu.items_mut().insert(*candidate, (Linkage::Internal, Visibility::Default));
213 }
214 }
215
216 return;
217 }
218
219 // Build a map from every monomorphization to all the monomorphizations that
220 // reference it.
221 let mut accessor_map: FxHashMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>> = Default::default();
1b1a35ee 222 cx.inlining_map.iter_accesses(|accessor, accessees| {
3dfed10e
XL
223 for accessee in accessees {
224 accessor_map.entry(*accessee).or_default().push(accessor);
225 }
226 });
227
228 let mono_item_placements = &partitioning.mono_item_placements;
229
230 // For each internalization candidates in each codegen unit, check if it is
231 // accessed from outside its defining codegen unit.
232 for cgu in &mut partitioning.codegen_units {
233 let home_cgu = MonoItemPlacement::SingleCgu { cgu_name: cgu.name() };
234
235 for (accessee, linkage_and_visibility) in cgu.items_mut() {
236 if !partitioning.internalization_candidates.contains(accessee) {
237 // This item is no candidate for internalizing, so skip it.
238 continue;
239 }
240 debug_assert_eq!(mono_item_placements[accessee], home_cgu);
241
242 if let Some(accessors) = accessor_map.get(accessee) {
243 if accessors
244 .iter()
245 .filter_map(|accessor| {
246 // Some accessors might not have been
247 // instantiated. We can safely ignore those.
248 mono_item_placements.get(accessor)
249 })
250 .any(|placement| *placement != home_cgu)
251 {
252 // Found an accessor from another CGU, so skip to the next
253 // item without marking this one as internal.
254 continue;
255 }
256 }
257
258 // If we got here, we did not find any accesses from other CGUs,
259 // so it's fine to make this monomorphization internal.
260 *linkage_and_visibility = (Linkage::Internal, Visibility::Default);
261 }
262 }
263 }
264}
265
266fn characteristic_def_id_of_mono_item<'tcx>(
267 tcx: TyCtxt<'tcx>,
268 mono_item: MonoItem<'tcx>,
269) -> Option<DefId> {
270 match mono_item {
271 MonoItem::Fn(instance) => {
272 let def_id = match instance.def {
273 ty::InstanceDef::Item(def) => def.did,
274 ty::InstanceDef::VtableShim(..)
275 | ty::InstanceDef::ReifyShim(..)
276 | ty::InstanceDef::FnPtrShim(..)
277 | ty::InstanceDef::ClosureOnceShim { .. }
278 | ty::InstanceDef::Intrinsic(..)
279 | ty::InstanceDef::DropGlue(..)
280 | ty::InstanceDef::Virtual(..)
281 | ty::InstanceDef::CloneShim(..) => return None,
282 };
283
284 // If this is a method, we want to put it into the same module as
285 // its self-type. If the self-type does not provide a characteristic
286 // DefId, we use the location of the impl after all.
287
288 if tcx.trait_of_item(def_id).is_some() {
289 let self_ty = instance.substs.type_at(0);
290 // This is a default implementation of a trait method.
291 return characteristic_def_id_of_type(self_ty).or(Some(def_id));
292 }
293
294 if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
295 if tcx.sess.opts.incremental.is_some()
296 && tcx.trait_id_of_impl(impl_def_id) == tcx.lang_items().drop_trait()
297 {
298 // Put `Drop::drop` into the same cgu as `drop_in_place`
299 // since `drop_in_place` is the only thing that can
300 // call it.
301 return None;
302 }
303 // This is a method within an impl, find out what the self-type is:
304 let impl_self_ty = tcx.subst_and_normalize_erasing_regions(
305 instance.substs,
306 ty::ParamEnv::reveal_all(),
fc512014 307 tcx.type_of(impl_def_id),
3dfed10e
XL
308 );
309 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
310 return Some(def_id);
311 }
312 }
313
314 Some(def_id)
315 }
316 MonoItem::Static(def_id) => Some(def_id),
6a06907d 317 MonoItem::GlobalAsm(item_id) => Some(item_id.def_id.to_def_id()),
3dfed10e
XL
318 }
319}
320
321fn compute_codegen_unit_name(
322 tcx: TyCtxt<'_>,
323 name_builder: &mut CodegenUnitNameBuilder<'_>,
324 def_id: DefId,
325 volatile: bool,
326 cache: &mut CguNameCache,
327) -> Symbol {
328 // Find the innermost module that is not nested within a function.
329 let mut current_def_id = def_id;
330 let mut cgu_def_id = None;
331 // Walk backwards from the item we want to find the module for.
332 loop {
333 if current_def_id.index == CRATE_DEF_INDEX {
334 if cgu_def_id.is_none() {
335 // If we have not found a module yet, take the crate root.
336 cgu_def_id = Some(DefId { krate: def_id.krate, index: CRATE_DEF_INDEX });
337 }
338 break;
339 } else if tcx.def_kind(current_def_id) == DefKind::Mod {
340 if cgu_def_id.is_none() {
341 cgu_def_id = Some(current_def_id);
342 }
343 } else {
344 // If we encounter something that is not a module, throw away
345 // any module that we've found so far because we now know that
346 // it is nested within something else.
347 cgu_def_id = None;
348 }
349
350 current_def_id = tcx.parent(current_def_id).unwrap();
351 }
352
353 let cgu_def_id = cgu_def_id.unwrap();
354
355 *cache.entry((cgu_def_id, volatile)).or_insert_with(|| {
356 let def_path = tcx.def_path(cgu_def_id);
357
1b1a35ee
XL
358 let components = def_path.data.iter().map(|part| match part.data.name() {
359 DefPathDataName::Named(name) => name,
360 DefPathDataName::Anon { .. } => unreachable!(),
361 });
3dfed10e
XL
362
363 let volatile_suffix = volatile.then_some("volatile");
364
365 name_builder.build_cgu_name(def_path.krate, components, volatile_suffix)
366 })
367}
368
369// Anything we can't find a proper codegen unit for goes into this.
370fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_>) -> Symbol {
371 name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu"))
372}
373
374fn mono_item_linkage_and_visibility(
375 tcx: TyCtxt<'tcx>,
376 mono_item: &MonoItem<'tcx>,
377 can_be_internalized: &mut bool,
378 export_generics: bool,
379) -> (Linkage, Visibility) {
380 if let Some(explicit_linkage) = mono_item.explicit_linkage(tcx) {
381 return (explicit_linkage, Visibility::Default);
382 }
383 let vis = mono_item_visibility(tcx, mono_item, can_be_internalized, export_generics);
384 (Linkage::External, vis)
385}
386
387type CguNameCache = FxHashMap<(DefId, bool), Symbol>;
388
389fn mono_item_visibility(
390 tcx: TyCtxt<'tcx>,
391 mono_item: &MonoItem<'tcx>,
392 can_be_internalized: &mut bool,
393 export_generics: bool,
394) -> Visibility {
395 let instance = match mono_item {
396 // This is pretty complicated; see below.
397 MonoItem::Fn(instance) => instance,
398
399 // Misc handling for generics and such, but otherwise:
400 MonoItem::Static(def_id) => {
401 return if tcx.is_reachable_non_generic(*def_id) {
402 *can_be_internalized = false;
403 default_visibility(tcx, *def_id, false)
404 } else {
405 Visibility::Hidden
406 };
407 }
6a06907d
XL
408 MonoItem::GlobalAsm(item_id) => {
409 return if tcx.is_reachable_non_generic(item_id.def_id) {
3dfed10e 410 *can_be_internalized = false;
6a06907d 411 default_visibility(tcx, item_id.def_id.to_def_id(), false)
3dfed10e
XL
412 } else {
413 Visibility::Hidden
414 };
415 }
416 };
417
418 let def_id = match instance.def {
419 InstanceDef::Item(def) => def.did,
420 InstanceDef::DropGlue(def_id, Some(_)) => def_id,
421
422 // These are all compiler glue and such, never exported, always hidden.
423 InstanceDef::VtableShim(..)
424 | InstanceDef::ReifyShim(..)
425 | InstanceDef::FnPtrShim(..)
426 | InstanceDef::Virtual(..)
427 | InstanceDef::Intrinsic(..)
428 | InstanceDef::ClosureOnceShim { .. }
429 | InstanceDef::DropGlue(..)
430 | InstanceDef::CloneShim(..) => return Visibility::Hidden,
431 };
432
433 // The `start_fn` lang item is actually a monomorphized instance of a
434 // function in the standard library, used for the `main` function. We don't
435 // want to export it so we tag it with `Hidden` visibility but this symbol
436 // is only referenced from the actual `main` symbol which we unfortunately
437 // don't know anything about during partitioning/collection. As a result we
438 // forcibly keep this symbol out of the `internalization_candidates` set.
439 //
440 // FIXME: eventually we don't want to always force this symbol to have
441 // hidden visibility, it should indeed be a candidate for
442 // internalization, but we have to understand that it's referenced
443 // from the `main` symbol we'll generate later.
444 //
445 // This may be fixable with a new `InstanceDef` perhaps? Unsure!
446 if tcx.lang_items().start_fn() == Some(def_id) {
447 *can_be_internalized = false;
448 return Visibility::Hidden;
449 }
450
451 let is_generic = instance.substs.non_erasable_generics().next().is_some();
452
453 // Upstream `DefId` instances get different handling than local ones.
17df50a5
XL
454 let def_id = if let Some(def_id) = def_id.as_local() {
455 def_id
456 } else {
3dfed10e 457 return if export_generics && is_generic {
94222f64 458 // If it is an upstream monomorphization and we export generics, we must make
3dfed10e
XL
459 // it available to downstream crates.
460 *can_be_internalized = false;
461 default_visibility(tcx, def_id, true)
462 } else {
463 Visibility::Hidden
464 };
17df50a5 465 };
3dfed10e
XL
466
467 if is_generic {
468 if export_generics {
469 if tcx.is_unreachable_local_definition(def_id) {
470 // This instance cannot be used from another crate.
471 Visibility::Hidden
472 } else {
473 // This instance might be useful in a downstream crate.
474 *can_be_internalized = false;
17df50a5 475 default_visibility(tcx, def_id.to_def_id(), true)
3dfed10e
XL
476 }
477 } else {
478 // We are not exporting generics or the definition is not reachable
479 // for downstream crates, we can internalize its instantiations.
480 Visibility::Hidden
481 }
482 } else {
483 // If this isn't a generic function then we mark this a `Default` if
484 // this is a reachable item, meaning that it's a symbol other crates may
485 // access when they link to us.
17df50a5 486 if tcx.is_reachable_non_generic(def_id.to_def_id()) {
3dfed10e
XL
487 *can_be_internalized = false;
488 debug_assert!(!is_generic);
17df50a5 489 return default_visibility(tcx, def_id.to_def_id(), false);
3dfed10e
XL
490 }
491
492 // If this isn't reachable then we're gonna tag this with `Hidden`
493 // visibility. In some situations though we'll want to prevent this
494 // symbol from being internalized.
495 //
496 // There's two categories of items here:
497 //
498 // * First is weak lang items. These are basically mechanisms for
499 // libcore to forward-reference symbols defined later in crates like
500 // the standard library or `#[panic_handler]` definitions. The
501 // definition of these weak lang items needs to be referenceable by
502 // libcore, so we're no longer a candidate for internalization.
503 // Removal of these functions can't be done by LLVM but rather must be
504 // done by the linker as it's a non-local decision.
505 //
506 // * Second is "std internal symbols". Currently this is primarily used
507 // for allocator symbols. Allocators are a little weird in their
508 // implementation, but the idea is that the compiler, at the last
509 // minute, defines an allocator with an injected object file. The
510 // `alloc` crate references these symbols (`__rust_alloc`) and the
511 // definition doesn't get hooked up until a linked crate artifact is
512 // generated.
513 //
514 // The symbols synthesized by the compiler (`__rust_alloc`) are thin
515 // veneers around the actual implementation, some other symbol which
516 // implements the same ABI. These symbols (things like `__rg_alloc`,
517 // `__rdl_alloc`, `__rde_alloc`, etc), are all tagged with "std
518 // internal symbols".
519 //
520 // The std-internal symbols here **should not show up in a dll as an
521 // exported interface**, so they return `false` from
522 // `is_reachable_non_generic` above and we'll give them `Hidden`
523 // visibility below. Like the weak lang items, though, we can't let
524 // LLVM internalize them as this decision is left up to the linker to
525 // omit them, so prevent them from being internalized.
526 let attrs = tcx.codegen_fn_attrs(def_id);
527 if attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
528 *can_be_internalized = false;
529 }
530
531 Visibility::Hidden
532 }
533}
534
535fn default_visibility(tcx: TyCtxt<'_>, id: DefId, is_generic: bool) -> Visibility {
29967ef6 536 if !tcx.sess.target.default_hidden_visibility {
3dfed10e
XL
537 return Visibility::Default;
538 }
539
540 // Generic functions never have export-level C.
541 if is_generic {
542 return Visibility::Hidden;
543 }
544
545 // Things with export level C don't get instantiated in
546 // downstream crates.
547 if !id.is_local() {
548 return Visibility::Hidden;
549 }
550
551 // C-export level items remain at `Default`, all other internal
552 // items become `Hidden`.
553 match tcx.reachable_non_generics(id.krate).get(&id) {
554 Some(SymbolExportLevel::C) => Visibility::Default,
555 _ => Visibility::Hidden,
556 }
557}