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