1use std::cmp;
96use std::collections::hash_map::Entry;
97use std::fs::{self, File};
98use std::io::Write;
99use std::path::{Path, PathBuf};
100
101use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
102use rustc_data_structures::sync;
103use rustc_data_structures::unord::{UnordMap, UnordSet};
104use rustc_hir::LangItem;
105use rustc_hir::attrs::{InlineAttr, Linkage};
106use rustc_hir::def::DefKind;
107use rustc_hir::def_id::{DefId, DefIdSet, LOCAL_CRATE};
108use rustc_hir::definitions::DefPathDataName;
109use rustc_middle::bug;
110use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
111use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
112use rustc_middle::mir::mono::{
113 CodegenUnit, CodegenUnitNameBuilder, InstantiationMode, MonoItem, MonoItemData,
114 MonoItemPartitions, Visibility,
115};
116use rustc_middle::ty::print::{characteristic_def_id_of_type, with_no_trimmed_paths};
117use rustc_middle::ty::{self, InstanceKind, TyCtxt};
118use rustc_middle::util::Providers;
119use rustc_session::CodegenUnits;
120use rustc_session::config::{DumpMonoStatsFormat, SwitchWithOptPath};
121use rustc_span::Symbol;
122use rustc_target::spec::SymbolVisibility;
123use tracing::debug;
124
125use crate::collector::{self, MonoItemCollectionStrategy, UsageMap};
126use crate::errors::{CouldntDumpMonoStats, SymbolAlreadyDefined};
127
128struct PartitioningCx<'a, 'tcx> {
129 tcx: TyCtxt<'tcx>,
130 usage_map: &'a UsageMap<'tcx>,
131}
132
133struct PlacedMonoItems<'tcx> {
134 codegen_units: Vec<CodegenUnit<'tcx>>,
136
137 internalization_candidates: UnordSet<MonoItem<'tcx>>,
138}
139
140fn partition<'tcx, I>(
142 tcx: TyCtxt<'tcx>,
143 mono_items: I,
144 usage_map: &UsageMap<'tcx>,
145) -> Vec<CodegenUnit<'tcx>>
146where
147 I: Iterator<Item = MonoItem<'tcx>>,
148{
149 let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
150
151 let cx = &PartitioningCx { tcx, usage_map };
152
153 let PlacedMonoItems { mut codegen_units, internalization_candidates } = {
156 let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_items");
157 let placed = place_mono_items(cx, mono_items);
158
159 debug_dump(tcx, "PLACE", &placed.codegen_units);
160
161 placed
162 };
163
164 {
168 let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus");
169 merge_codegen_units(cx, &mut codegen_units);
170 debug_dump(tcx, "MERGE", &codegen_units);
171 }
172
173 if !tcx.sess.link_dead_code() {
176 let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_internalize_symbols");
177 internalize_symbols(cx, &mut codegen_units, internalization_candidates);
178
179 debug_dump(tcx, "INTERNALIZE", &codegen_units);
180 }
181
182 if tcx.sess.instrument_coverage() {
184 mark_code_coverage_dead_code_cgu(&mut codegen_units);
185 }
186
187 if !codegen_units.is_sorted_by(|a, b| a.name().as_str() <= b.name().as_str()) {
189 let mut names = String::new();
190 for cgu in codegen_units.iter() {
191 names += &format!("- {}\n", cgu.name());
192 }
193 bug!("unsorted CGUs:\n{names}");
194 }
195
196 codegen_units
197}
198
199fn place_mono_items<'tcx, I>(cx: &PartitioningCx<'_, 'tcx>, mono_items: I) -> PlacedMonoItems<'tcx>
200where
201 I: Iterator<Item = MonoItem<'tcx>>,
202{
203 let mut codegen_units = UnordMap::default();
204 let is_incremental_build = cx.tcx.sess.opts.incremental.is_some();
205 let mut internalization_candidates = UnordSet::default();
206
207 let can_export_generics = cx.tcx.local_crate_exports_generics();
212 let always_export_generics = can_export_generics && cx.tcx.sess.opts.share_generics();
213
214 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
215 let cgu_name_cache = &mut UnordMap::default();
216
217 for mono_item in mono_items {
218 match mono_item.instantiation_mode(cx.tcx) {
223 InstantiationMode::GloballyShared { .. } => {}
224 InstantiationMode::LocalCopy => continue,
225 }
226
227 let characteristic_def_id = characteristic_def_id_of_mono_item(cx.tcx, mono_item);
228 let is_volatile = is_incremental_build && mono_item.is_generic_fn();
229
230 let cgu_name = match characteristic_def_id {
231 Some(def_id) => compute_codegen_unit_name(
232 cx.tcx,
233 cgu_name_builder,
234 def_id,
235 is_volatile,
236 cgu_name_cache,
237 ),
238 None => fallback_cgu_name(cgu_name_builder),
239 };
240
241 let cgu = codegen_units.entry(cgu_name).or_insert_with(|| CodegenUnit::new(cgu_name));
242
243 let mut can_be_internalized = true;
244 let (linkage, visibility) = mono_item_linkage_and_visibility(
245 cx.tcx,
246 &mono_item,
247 &mut can_be_internalized,
248 can_export_generics,
249 always_export_generics,
250 );
251
252 if visibility == Visibility::Hidden && can_be_internalized {
253 internalization_candidates.insert(mono_item);
254 }
255 let size_estimate = mono_item.size_estimate(cx.tcx);
256
257 cgu.items_mut()
258 .insert(mono_item, MonoItemData { inlined: false, linkage, visibility, size_estimate });
259
260 let mut reachable_inlined_items = FxIndexSet::default();
265 get_reachable_inlined_items(cx.tcx, mono_item, cx.usage_map, &mut reachable_inlined_items);
266
267 for inlined_item in reachable_inlined_items {
271 cgu.items_mut().entry(inlined_item).or_insert_with(|| MonoItemData {
273 inlined: true,
274 linkage: Linkage::Internal,
275 visibility: Visibility::Default,
276 size_estimate: inlined_item.size_estimate(cx.tcx),
277 });
278 }
279 }
280
281 if codegen_units.is_empty() {
284 let cgu_name = fallback_cgu_name(cgu_name_builder);
285 codegen_units.insert(cgu_name, CodegenUnit::new(cgu_name));
286 }
287
288 let mut codegen_units: Vec<_> = cx.tcx.with_stable_hashing_context(|ref hcx| {
289 codegen_units.into_items().map(|(_, cgu)| cgu).collect_sorted(hcx, true)
290 });
291
292 for cgu in codegen_units.iter_mut() {
293 cgu.compute_size_estimate();
294 }
295
296 return PlacedMonoItems { codegen_units, internalization_candidates };
297
298 fn get_reachable_inlined_items<'tcx>(
299 tcx: TyCtxt<'tcx>,
300 item: MonoItem<'tcx>,
301 usage_map: &UsageMap<'tcx>,
302 visited: &mut FxIndexSet<MonoItem<'tcx>>,
303 ) {
304 usage_map.for_each_inlined_used_item(tcx, item, |inlined_item| {
305 let is_new = visited.insert(inlined_item);
306 if is_new {
307 get_reachable_inlined_items(tcx, inlined_item, usage_map, visited);
308 }
309 });
310 }
311}
312
313fn merge_codegen_units<'tcx>(
316 cx: &PartitioningCx<'_, 'tcx>,
317 codegen_units: &mut Vec<CodegenUnit<'tcx>>,
318) {
319 assert!(cx.tcx.sess.codegen_units().as_usize() >= 1);
320
321 assert!(codegen_units.is_sorted_by(|a, b| a.name().as_str() <= b.name().as_str()));
323
324 let mut cgu_contents: UnordMap<Symbol, Vec<Symbol>> =
326 codegen_units.iter().map(|cgu| (cgu.name(), vec![cgu.name()])).collect();
327
328 let max_codegen_units = cx.tcx.sess.codegen_units().as_usize();
343 while codegen_units.len() > max_codegen_units {
344 codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
346
347 let cgu_dst = &codegen_units[max_codegen_units - 1];
348
349 let mut max_overlap = 0;
352 let mut max_overlap_i = max_codegen_units;
353 for (i, cgu_src) in codegen_units.iter().enumerate().skip(max_codegen_units) {
354 if cgu_src.size_estimate() <= max_overlap {
355 break;
358 }
359
360 let overlap = compute_inlined_overlap(cgu_dst, cgu_src);
361 if overlap > max_overlap {
362 max_overlap = overlap;
363 max_overlap_i = i;
364 }
365 }
366
367 let mut cgu_src = codegen_units.swap_remove(max_overlap_i);
368 let cgu_dst = &mut codegen_units[max_codegen_units - 1];
369
370 cgu_dst.items_mut().append(cgu_src.items_mut());
374 cgu_dst.compute_size_estimate();
375
376 let mut consumed_cgu_names = cgu_contents.remove(&cgu_src.name()).unwrap();
379 cgu_contents.get_mut(&cgu_dst.name()).unwrap().append(&mut consumed_cgu_names);
380 }
381
382 const NON_INCR_MIN_CGU_SIZE: usize = 1800;
388
389 while cx.tcx.sess.opts.incremental.is_none()
399 && matches!(cx.tcx.sess.codegen_units(), CodegenUnits::Default(_))
400 && codegen_units.len() > 1
401 && codegen_units.iter().any(|cgu| cgu.size_estimate() < NON_INCR_MIN_CGU_SIZE)
402 {
403 codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
405
406 let mut smallest = codegen_units.pop().unwrap();
407 let second_smallest = codegen_units.last_mut().unwrap();
408
409 second_smallest.items_mut().append(smallest.items_mut());
413 second_smallest.compute_size_estimate();
414
415 }
417
418 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
419
420 if cx.tcx.sess.opts.incremental.is_some() {
422 let new_cgu_names = UnordMap::from(
428 cgu_contents
429 .items()
430 .filter(|(_, cgu_contents)| cgu_contents.len() > 1)
433 .map(|(current_cgu_name, cgu_contents)| {
434 let mut cgu_contents: Vec<&str> =
435 cgu_contents.iter().map(|s| s.as_str()).collect();
436
437 cgu_contents.sort_unstable();
441
442 (*current_cgu_name, cgu_contents.join("--"))
443 }),
444 );
445
446 for cgu in codegen_units.iter_mut() {
447 if let Some(new_cgu_name) = new_cgu_names.get(&cgu.name()) {
448 let new_cgu_name = if cx.tcx.sess.opts.unstable_opts.human_readable_cgu_names {
449 Symbol::intern(&CodegenUnit::shorten_name(new_cgu_name))
450 } else {
451 Symbol::intern(&CodegenUnit::mangle_name(new_cgu_name))
455 };
456 cgu.set_name(new_cgu_name);
457 }
458 }
459
460 codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str()));
462 } else {
463 codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
483 let num_digits = codegen_units.len().ilog10() as usize + 1;
484 for (index, cgu) in codegen_units.iter_mut().enumerate() {
485 let suffix = format!("{index:0num_digits$}");
489 let numbered_codegen_unit_name =
490 cgu_name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(suffix));
491 cgu.set_name(numbered_codegen_unit_name);
492 }
493 }
494}
495
496fn compute_inlined_overlap<'tcx>(cgu1: &CodegenUnit<'tcx>, cgu2: &CodegenUnit<'tcx>) -> usize {
499 let (src_cgu, dst_cgu) =
502 if cgu1.items().len() <= cgu2.items().len() { (cgu1, cgu2) } else { (cgu2, cgu1) };
503
504 let mut overlap = 0;
505 for (item, data) in src_cgu.items().iter() {
506 if data.inlined && dst_cgu.items().contains_key(item) {
507 overlap += data.size_estimate;
508 }
509 }
510 overlap
511}
512
513fn internalize_symbols<'tcx>(
514 cx: &PartitioningCx<'_, 'tcx>,
515 codegen_units: &mut [CodegenUnit<'tcx>],
516 internalization_candidates: UnordSet<MonoItem<'tcx>>,
517) {
518 #[derive(Clone, PartialEq, Eq, Debug)]
522 enum MonoItemPlacement {
523 SingleCgu(Symbol),
524 MultipleCgus,
525 }
526
527 let mut mono_item_placements = UnordMap::default();
528 let single_codegen_unit = codegen_units.len() == 1;
529
530 if !single_codegen_unit {
531 for cgu in codegen_units.iter() {
532 for item in cgu.items().keys() {
533 match mono_item_placements.entry(*item) {
536 Entry::Occupied(e) => {
537 let placement = e.into_mut();
538 debug_assert!(match *placement {
539 MonoItemPlacement::SingleCgu(cgu_name) => cgu_name != cgu.name(),
540 MonoItemPlacement::MultipleCgus => true,
541 });
542 *placement = MonoItemPlacement::MultipleCgus;
543 }
544 Entry::Vacant(e) => {
545 e.insert(MonoItemPlacement::SingleCgu(cgu.name()));
546 }
547 }
548 }
549 }
550 }
551
552 for cgu in codegen_units {
555 let home_cgu = MonoItemPlacement::SingleCgu(cgu.name());
556
557 for (item, data) in cgu.items_mut() {
558 if !internalization_candidates.contains(item) {
559 continue;
561 }
562
563 if !single_codegen_unit {
564 debug_assert_eq!(mono_item_placements[item], home_cgu);
565
566 if cx
567 .usage_map
568 .get_user_items(*item)
569 .iter()
570 .filter_map(|user_item| {
571 mono_item_placements.get(user_item)
574 })
575 .any(|placement| *placement != home_cgu)
576 {
577 continue;
580 }
581 }
582
583 if let MonoItem::Fn(instance) = item {
587 let flags = cx.tcx.codegen_instance_attrs(instance.def).flags;
588 if flags.contains(CodegenFnAttrFlags::NAKED) {
589 continue;
590 }
591 }
592
593 data.linkage = Linkage::Internal;
596 data.visibility = Visibility::Default;
597 }
598 }
599}
600
601fn mark_code_coverage_dead_code_cgu<'tcx>(codegen_units: &mut [CodegenUnit<'tcx>]) {
602 assert!(!codegen_units.is_empty());
603
604 let dead_code_cgu = codegen_units
612 .iter_mut()
613 .filter(|cgu| cgu.items().iter().any(|(_, data)| data.linkage == Linkage::External))
614 .min_by_key(|cgu| cgu.size_estimate());
615
616 let dead_code_cgu = if let Some(cgu) = dead_code_cgu { cgu } else { &mut codegen_units[0] };
619
620 dead_code_cgu.make_code_coverage_dead_code_cgu();
621}
622
623fn characteristic_def_id_of_mono_item<'tcx>(
624 tcx: TyCtxt<'tcx>,
625 mono_item: MonoItem<'tcx>,
626) -> Option<DefId> {
627 match mono_item {
628 MonoItem::Fn(instance) => {
629 let def_id = match instance.def {
630 ty::InstanceKind::Item(def) => def,
631 ty::InstanceKind::VTableShim(..)
632 | ty::InstanceKind::ReifyShim(..)
633 | ty::InstanceKind::FnPtrShim(..)
634 | ty::InstanceKind::ClosureOnceShim { .. }
635 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
636 | ty::InstanceKind::Intrinsic(..)
637 | ty::InstanceKind::DropGlue(..)
638 | ty::InstanceKind::Virtual(..)
639 | ty::InstanceKind::CloneShim(..)
640 | ty::InstanceKind::ThreadLocalShim(..)
641 | ty::InstanceKind::FnPtrAddrShim(..)
642 | ty::InstanceKind::FutureDropPollShim(..)
643 | ty::InstanceKind::AsyncDropGlue(..)
644 | ty::InstanceKind::AsyncDropGlueCtorShim(..) => return None,
645 };
646
647 let assoc_parent = tcx.assoc_parent(def_id);
652
653 if let Some((_, DefKind::Trait)) = assoc_parent {
654 let self_ty = instance.args.type_at(0);
655 return characteristic_def_id_of_type(self_ty).or(Some(def_id));
657 }
658
659 if let Some((impl_def_id, DefKind::Impl { of_trait })) = assoc_parent {
660 if of_trait
661 && tcx.sess.opts.incremental.is_some()
662 && tcx.is_lang_item(tcx.impl_trait_id(impl_def_id), LangItem::Drop)
663 {
664 return None;
668 }
669
670 let impl_self_ty = tcx.instantiate_and_normalize_erasing_regions(
672 instance.args,
673 ty::TypingEnv::fully_monomorphized(),
674 tcx.type_of(impl_def_id),
675 );
676 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
677 return Some(def_id);
678 }
679 }
680
681 Some(def_id)
682 }
683 MonoItem::Static(def_id) => Some(def_id),
684 MonoItem::GlobalAsm(item_id) => Some(item_id.owner_id.to_def_id()),
685 }
686}
687
688fn compute_codegen_unit_name(
689 tcx: TyCtxt<'_>,
690 name_builder: &mut CodegenUnitNameBuilder<'_>,
691 def_id: DefId,
692 volatile: bool,
693 cache: &mut CguNameCache,
694) -> Symbol {
695 let mut current_def_id = def_id;
697 let mut cgu_def_id = None;
698 loop {
700 if current_def_id.is_crate_root() {
701 if cgu_def_id.is_none() {
702 cgu_def_id = Some(def_id.krate.as_def_id());
704 }
705 break;
706 } else if tcx.def_kind(current_def_id) == DefKind::Mod {
707 if cgu_def_id.is_none() {
708 cgu_def_id = Some(current_def_id);
709 }
710 } else {
711 cgu_def_id = None;
715 }
716
717 current_def_id = tcx.parent(current_def_id);
718 }
719
720 let cgu_def_id = cgu_def_id.unwrap();
721
722 *cache.entry((cgu_def_id, volatile)).or_insert_with(|| {
723 let def_path = tcx.def_path(cgu_def_id);
724
725 let components = def_path.data.iter().map(|part| match part.data.name() {
726 DefPathDataName::Named(name) => name,
727 DefPathDataName::Anon { .. } => unreachable!(),
728 });
729
730 let volatile_suffix = volatile.then_some("volatile");
731
732 name_builder.build_cgu_name(def_path.krate, components, volatile_suffix)
733 })
734}
735
736fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_>) -> Symbol {
738 name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu"))
739}
740
741fn mono_item_linkage_and_visibility<'tcx>(
742 tcx: TyCtxt<'tcx>,
743 mono_item: &MonoItem<'tcx>,
744 can_be_internalized: &mut bool,
745 can_export_generics: bool,
746 always_export_generics: bool,
747) -> (Linkage, Visibility) {
748 if let Some(explicit_linkage) = mono_item.explicit_linkage(tcx) {
749 return (explicit_linkage, Visibility::Default);
750 }
751 let vis = mono_item_visibility(
752 tcx,
753 mono_item,
754 can_be_internalized,
755 can_export_generics,
756 always_export_generics,
757 );
758 (Linkage::External, vis)
759}
760
761type CguNameCache = UnordMap<(DefId, bool), Symbol>;
762
763fn static_visibility<'tcx>(
764 tcx: TyCtxt<'tcx>,
765 can_be_internalized: &mut bool,
766 def_id: DefId,
767) -> Visibility {
768 if tcx.is_reachable_non_generic(def_id) {
769 *can_be_internalized = false;
770 default_visibility(tcx, def_id, false)
771 } else {
772 Visibility::Hidden
773 }
774}
775
776fn mono_item_visibility<'tcx>(
777 tcx: TyCtxt<'tcx>,
778 mono_item: &MonoItem<'tcx>,
779 can_be_internalized: &mut bool,
780 can_export_generics: bool,
781 always_export_generics: bool,
782) -> Visibility {
783 let instance = match mono_item {
784 MonoItem::Fn(instance) => instance,
786
787 MonoItem::Static(def_id) => return static_visibility(tcx, can_be_internalized, *def_id),
789 MonoItem::GlobalAsm(item_id) => {
790 return static_visibility(tcx, can_be_internalized, item_id.owner_id.to_def_id());
791 }
792 };
793
794 let def_id = match instance.def {
795 InstanceKind::Item(def_id)
796 | InstanceKind::DropGlue(def_id, Some(_))
797 | InstanceKind::FutureDropPollShim(def_id, _, _)
798 | InstanceKind::AsyncDropGlue(def_id, _)
799 | InstanceKind::AsyncDropGlueCtorShim(def_id, _) => def_id,
800
801 InstanceKind::ThreadLocalShim(def_id) => {
803 return static_visibility(tcx, can_be_internalized, def_id);
804 }
805
806 InstanceKind::VTableShim(..)
808 | InstanceKind::ReifyShim(..)
809 | InstanceKind::FnPtrShim(..)
810 | InstanceKind::Virtual(..)
811 | InstanceKind::Intrinsic(..)
812 | InstanceKind::ClosureOnceShim { .. }
813 | InstanceKind::ConstructCoroutineInClosureShim { .. }
814 | InstanceKind::DropGlue(..)
815 | InstanceKind::CloneShim(..)
816 | InstanceKind::FnPtrAddrShim(..) => return Visibility::Hidden,
817 };
818
819 if tcx.is_entrypoint(def_id) {
832 *can_be_internalized = false;
833 return Visibility::Hidden;
834 }
835
836 let is_generic = instance.args.non_erasable_generics().next().is_some();
837
838 let Some(def_id) = def_id.as_local() else {
840 return if is_generic
841 && (always_export_generics
842 || (can_export_generics
843 && tcx.codegen_fn_attrs(def_id).inline == InlineAttr::Never))
844 {
845 *can_be_internalized = false;
848 default_visibility(tcx, def_id, true)
849 } else {
850 Visibility::Hidden
851 };
852 };
853
854 if is_generic {
855 if always_export_generics
856 || (can_export_generics && tcx.codegen_fn_attrs(def_id).inline == InlineAttr::Never)
857 {
858 if tcx.is_unreachable_local_definition(def_id) {
859 Visibility::Hidden
861 } else {
862 *can_be_internalized = false;
864 default_visibility(tcx, def_id.to_def_id(), true)
865 }
866 } else {
867 Visibility::Hidden
870 }
871 } else {
872 if tcx.is_reachable_non_generic(def_id.to_def_id()) {
876 *can_be_internalized = false;
877 debug_assert!(!is_generic);
878 return default_visibility(tcx, def_id.to_def_id(), false);
879 }
880
881 let attrs = tcx.codegen_fn_attrs(def_id);
921 if attrs.flags.intersects(
922 CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
923 | CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM,
924 ) {
925 *can_be_internalized = false;
926 }
927
928 Visibility::Hidden
929 }
930}
931
932fn default_visibility(tcx: TyCtxt<'_>, id: DefId, is_generic: bool) -> Visibility {
933 if tcx.sess.default_visibility() == SymbolVisibility::Interposable {
935 return Visibility::Default;
936 }
937
938 let export_level = if is_generic {
939 SymbolExportLevel::Rust
941 } else {
942 match tcx.reachable_non_generics(id.krate).get(&id) {
943 Some(SymbolExportInfo { level: SymbolExportLevel::C, .. }) => SymbolExportLevel::C,
944 _ => SymbolExportLevel::Rust,
945 }
946 };
947
948 match export_level {
949 SymbolExportLevel::C => Visibility::Default,
952
953 SymbolExportLevel::Rust => tcx.sess.default_visibility().into(),
955 }
956}
957
958fn debug_dump<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx>, label: &str, cgus: &[CodegenUnit<'tcx>]) {
959 let dump = move || {
960 use std::fmt::Write;
961
962 let mut num_cgus = 0;
963 let mut all_cgu_sizes = Vec::new();
964
965 let mut inlined_items = UnordSet::default();
971
972 let mut root_items = 0;
973 let mut unique_inlined_items = 0;
974 let mut placed_inlined_items = 0;
975
976 let mut root_size = 0;
977 let mut unique_inlined_size = 0;
978 let mut placed_inlined_size = 0;
979
980 for cgu in cgus.iter() {
981 num_cgus += 1;
982 all_cgu_sizes.push(cgu.size_estimate());
983
984 for (item, data) in cgu.items() {
985 if !data.inlined {
986 root_items += 1;
987 root_size += data.size_estimate;
988 } else {
989 if inlined_items.insert(item) {
990 unique_inlined_items += 1;
991 unique_inlined_size += data.size_estimate;
992 }
993 placed_inlined_items += 1;
994 placed_inlined_size += data.size_estimate;
995 }
996 }
997 }
998
999 all_cgu_sizes.sort_unstable_by_key(|&n| cmp::Reverse(n));
1000
1001 let unique_items = root_items + unique_inlined_items;
1002 let placed_items = root_items + placed_inlined_items;
1003 let items_ratio = placed_items as f64 / unique_items as f64;
1004
1005 let unique_size = root_size + unique_inlined_size;
1006 let placed_size = root_size + placed_inlined_size;
1007 let size_ratio = placed_size as f64 / unique_size as f64;
1008
1009 let mean_cgu_size = placed_size as f64 / num_cgus as f64;
1010
1011 assert_eq!(placed_size, all_cgu_sizes.iter().sum::<usize>());
1012
1013 let s = &mut String::new();
1014 let _ = writeln!(s, "{label}");
1015 let _ = writeln!(
1016 s,
1017 "- unique items: {unique_items} ({root_items} root + {unique_inlined_items} inlined), \
1018 unique size: {unique_size} ({root_size} root + {unique_inlined_size} inlined)\n\
1019 - placed items: {placed_items} ({root_items} root + {placed_inlined_items} inlined), \
1020 placed size: {placed_size} ({root_size} root + {placed_inlined_size} inlined)\n\
1021 - placed/unique items ratio: {items_ratio:.2}, \
1022 placed/unique size ratio: {size_ratio:.2}\n\
1023 - CGUs: {num_cgus}, mean size: {mean_cgu_size:.1}, sizes: {}",
1024 list(&all_cgu_sizes),
1025 );
1026 let _ = writeln!(s);
1027
1028 for (i, cgu) in cgus.iter().enumerate() {
1029 let name = cgu.name();
1030 let size = cgu.size_estimate();
1031 let num_items = cgu.items().len();
1032 let mean_size = size as f64 / num_items as f64;
1033
1034 let mut placed_item_sizes: Vec<_> =
1035 cgu.items().values().map(|data| data.size_estimate).collect();
1036 placed_item_sizes.sort_unstable_by_key(|&n| cmp::Reverse(n));
1037 let sizes = list(&placed_item_sizes);
1038
1039 let _ = writeln!(s, "- CGU[{i}]");
1040 let _ = writeln!(s, " - {name}, size: {size}");
1041 let _ =
1042 writeln!(s, " - items: {num_items}, mean size: {mean_size:.1}, sizes: {sizes}",);
1043
1044 for (item, data) in cgu.items_in_deterministic_order(tcx) {
1045 let linkage = data.linkage;
1046 let symbol_name = item.symbol_name(tcx).name;
1047 let symbol_hash_start = symbol_name.rfind('h');
1048 let symbol_hash = symbol_hash_start.map_or("<no hash>", |i| &symbol_name[i..]);
1049 let kind = if !data.inlined { "root" } else { "inlined" };
1050 let size = data.size_estimate;
1051 let _ = with_no_trimmed_paths!(writeln!(
1052 s,
1053 " - {item} [{linkage:?}] [{symbol_hash}] ({kind}, size: {size})"
1054 ));
1055 }
1056
1057 let _ = writeln!(s);
1058 }
1059
1060 return std::mem::take(s);
1061
1062 fn list(ns: &[usize]) -> String {
1065 let mut v = Vec::new();
1066 if ns.is_empty() {
1067 return "[]".to_string();
1068 }
1069
1070 let mut elem = |curr, curr_count| {
1071 if curr_count == 1 {
1072 v.push(format!("{curr}"));
1073 } else {
1074 v.push(format!("{curr} (x{curr_count})"));
1075 }
1076 };
1077
1078 let mut curr = ns[0];
1079 let mut curr_count = 1;
1080
1081 for &n in &ns[1..] {
1082 if n != curr {
1083 elem(curr, curr_count);
1084 curr = n;
1085 curr_count = 1;
1086 } else {
1087 curr_count += 1;
1088 }
1089 }
1090 elem(curr, curr_count);
1091
1092 format!("[{}]", v.join(", "))
1093 }
1094 };
1095
1096 debug!("{}", dump());
1097}
1098
1099#[inline(never)] fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, mono_items: I)
1101where
1102 I: Iterator<Item = &'a MonoItem<'tcx>>,
1103 'tcx: 'a,
1104{
1105 let _prof_timer = tcx.prof.generic_activity("assert_symbols_are_distinct");
1106
1107 let mut symbols: Vec<_> =
1108 mono_items.map(|mono_item| (mono_item, mono_item.symbol_name(tcx))).collect();
1109
1110 symbols.sort_by_key(|sym| sym.1);
1111
1112 for &[(mono_item1, ref sym1), (mono_item2, ref sym2)] in symbols.array_windows() {
1113 if sym1 == sym2 {
1114 let span1 = mono_item1.local_span(tcx);
1115 let span2 = mono_item2.local_span(tcx);
1116
1117 let span = match (span1, span2) {
1119 (Some(span1), Some(span2)) => {
1120 Some(if span1.lo().0 > span2.lo().0 { span1 } else { span2 })
1121 }
1122 (span1, span2) => span1.or(span2),
1123 };
1124
1125 tcx.dcx().emit_fatal(SymbolAlreadyDefined { span, symbol: sym1.to_string() });
1126 }
1127 }
1128}
1129
1130fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> MonoItemPartitions<'_> {
1131 let collection_strategy = if tcx.sess.link_dead_code() {
1132 MonoItemCollectionStrategy::Eager
1133 } else {
1134 MonoItemCollectionStrategy::Lazy
1135 };
1136
1137 let (items, usage_map) = collector::collect_crate_mono_items(tcx, collection_strategy);
1138
1139 tcx.dcx().abort_if_errors();
1143
1144 let (codegen_units, _) = tcx.sess.time("partition_and_assert_distinct_symbols", || {
1145 sync::join(
1146 || {
1147 let mut codegen_units = partition(tcx, items.iter().copied(), &usage_map);
1148 codegen_units[0].make_primary();
1149 &*tcx.arena.alloc_from_iter(codegen_units)
1150 },
1151 || assert_symbols_are_distinct(tcx, items.iter()),
1152 )
1153 });
1154
1155 if tcx.prof.enabled() {
1156 for cgu in codegen_units {
1158 tcx.prof.artifact_size(
1159 "codegen_unit_size_estimate",
1160 cgu.name().as_str(),
1161 cgu.size_estimate() as u64,
1162 );
1163 }
1164 }
1165
1166 let mono_items: DefIdSet = items
1167 .iter()
1168 .filter_map(|mono_item| match *mono_item {
1169 MonoItem::Fn(ref instance) => Some(instance.def_id()),
1170 MonoItem::Static(def_id) => Some(def_id),
1171 _ => None,
1172 })
1173 .collect();
1174
1175 if let SwitchWithOptPath::Enabled(ref path) = tcx.sess.opts.unstable_opts.dump_mono_stats
1177 && let Err(err) =
1178 dump_mono_items_stats(tcx, codegen_units, path, tcx.crate_name(LOCAL_CRATE))
1179 {
1180 tcx.dcx().emit_fatal(CouldntDumpMonoStats { error: err.to_string() });
1181 }
1182
1183 if tcx.sess.opts.unstable_opts.print_mono_items {
1184 let mut item_to_cgus: UnordMap<_, Vec<_>> = Default::default();
1185
1186 for cgu in codegen_units {
1187 for (&mono_item, &data) in cgu.items() {
1188 item_to_cgus.entry(mono_item).or_default().push((cgu.name(), data.linkage));
1189 }
1190 }
1191
1192 let mut item_keys: Vec<_> = items
1193 .iter()
1194 .map(|i| {
1195 let mut output = with_no_trimmed_paths!(i.to_string());
1196 output.push_str(" @@");
1197 let mut empty = Vec::new();
1198 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1199 cgus.sort_by_key(|(name, _)| *name);
1200 cgus.dedup();
1201 for &(ref cgu_name, linkage) in cgus.iter() {
1202 output.push(' ');
1203 output.push_str(cgu_name.as_str());
1204
1205 let linkage_abbrev = match linkage {
1206 Linkage::External => "External",
1207 Linkage::AvailableExternally => "Available",
1208 Linkage::LinkOnceAny => "OnceAny",
1209 Linkage::LinkOnceODR => "OnceODR",
1210 Linkage::WeakAny => "WeakAny",
1211 Linkage::WeakODR => "WeakODR",
1212 Linkage::Internal => "Internal",
1213 Linkage::ExternalWeak => "ExternalWeak",
1214 Linkage::Common => "Common",
1215 };
1216
1217 output.push('[');
1218 output.push_str(linkage_abbrev);
1219 output.push(']');
1220 }
1221 output
1222 })
1223 .collect();
1224
1225 item_keys.sort();
1226
1227 for item in item_keys {
1228 println!("MONO_ITEM {item}");
1229 }
1230 }
1231
1232 MonoItemPartitions { all_mono_items: tcx.arena.alloc(mono_items), codegen_units }
1233}
1234
1235fn dump_mono_items_stats<'tcx>(
1238 tcx: TyCtxt<'tcx>,
1239 codegen_units: &[CodegenUnit<'tcx>],
1240 output_directory: &Option<PathBuf>,
1241 crate_name: Symbol,
1242) -> Result<(), Box<dyn std::error::Error>> {
1243 let output_directory = if let Some(directory) = output_directory {
1244 fs::create_dir_all(directory)?;
1245 directory
1246 } else {
1247 Path::new(".")
1248 };
1249
1250 let format = tcx.sess.opts.unstable_opts.dump_mono_stats_format;
1251 let ext = format.extension();
1252 let filename = format!("{crate_name}.mono_items.{ext}");
1253 let output_path = output_directory.join(&filename);
1254 let mut file = File::create_buffered(&output_path)?;
1255
1256 let mut items_per_def_id: FxIndexMap<_, Vec<_>> = Default::default();
1258 for cgu in codegen_units {
1259 cgu.items()
1260 .keys()
1261 .filter(|mono_item| mono_item.is_user_defined())
1263 .for_each(|mono_item| {
1264 items_per_def_id.entry(mono_item.def_id()).or_default().push(mono_item);
1265 });
1266 }
1267
1268 #[derive(serde::Serialize)]
1269 struct MonoItem {
1270 name: String,
1271 instantiation_count: usize,
1272 size_estimate: usize,
1273 total_estimate: usize,
1274 }
1275
1276 let mut stats: Vec<_> = items_per_def_id
1278 .into_iter()
1279 .map(|(def_id, items)| {
1280 let name = with_no_trimmed_paths!(tcx.def_path_str(def_id));
1281 let instantiation_count = items.len();
1282 let size_estimate = items[0].size_estimate(tcx);
1283 let total_estimate = instantiation_count * size_estimate;
1284 MonoItem { name, instantiation_count, size_estimate, total_estimate }
1285 })
1286 .collect();
1287 stats.sort_unstable_by_key(|item| cmp::Reverse(item.total_estimate));
1288
1289 if !stats.is_empty() {
1290 match format {
1291 DumpMonoStatsFormat::Json => serde_json::to_writer(file, &stats)?,
1292 DumpMonoStatsFormat::Markdown => {
1293 writeln!(
1294 file,
1295 "| Item | Instantiation count | Estimated Cost Per Instantiation | Total Estimated Cost |"
1296 )?;
1297 writeln!(file, "| --- | ---: | ---: | ---: |")?;
1298
1299 for MonoItem { name, instantiation_count, size_estimate, total_estimate } in stats {
1300 writeln!(
1301 file,
1302 "| `{name}` | {instantiation_count} | {size_estimate} | {total_estimate} |"
1303 )?;
1304 }
1305 }
1306 }
1307 }
1308
1309 Ok(())
1310}
1311
1312pub(crate) fn provide(providers: &mut Providers) {
1313 providers.collect_and_partition_mono_items = collect_and_partition_mono_items;
1314
1315 providers.is_codegened_item =
1316 |tcx, def_id| tcx.collect_and_partition_mono_items(()).all_mono_items.contains(&def_id);
1317
1318 providers.codegen_unit = |tcx, name| {
1319 tcx.collect_and_partition_mono_items(())
1320 .codegen_units
1321 .iter()
1322 .find(|cgu| cgu.name() == name)
1323 .unwrap_or_else(|| panic!("failed to find cgu with name {name:?}"))
1324 };
1325
1326 providers.size_estimate = |tcx, instance| {
1327 match instance.def {
1328 InstanceKind::Item(..)
1331 | InstanceKind::DropGlue(..)
1332 | InstanceKind::AsyncDropGlueCtorShim(..) => {
1333 let mir = tcx.instance_mir(instance.def);
1334 mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum()
1335 }
1336 _ => 1,
1338 }
1339 };
1340
1341 collector::provide(providers);
1342}