Skip to main content

rustc_monomorphize/
partitioning.rs

1//! Partitioning Codegen Units for Incremental Compilation
2//! ======================================================
3//!
4//! The task of this module is to take the complete set of monomorphizations of
5//! a crate and produce a set of codegen units from it, where a codegen unit
6//! is a named set of (mono-item, linkage) pairs. That is, this module
7//! decides which monomorphization appears in which codegen units with which
8//! linkage. The following paragraphs describe some of the background on the
9//! partitioning scheme.
10//!
11//! The most important opportunity for saving on compilation time with
12//! incremental compilation is to avoid re-codegenning and re-optimizing code.
13//! Since the unit of codegen and optimization for LLVM is "modules" or, how
14//! we call them "codegen units", the particulars of how much time can be saved
15//! by incremental compilation are tightly linked to how the output program is
16//! partitioned into these codegen units prior to passing it to LLVM --
17//! especially because we have to treat codegen units as opaque entities once
18//! they are created: There is no way for us to incrementally update an existing
19//! LLVM module and so we have to build any such module from scratch if it was
20//! affected by some change in the source code.
21//!
22//! From that point of view it would make sense to maximize the number of
23//! codegen units by, for example, putting each function into its own module.
24//! That way only those modules would have to be re-compiled that were actually
25//! affected by some change, minimizing the number of functions that could have
26//! been re-used but just happened to be located in a module that is
27//! re-compiled.
28//!
29//! However, since LLVM optimization does not work across module boundaries,
30//! using such a highly granular partitioning would lead to very slow runtime
31//! code since it would effectively prohibit inlining and other inter-procedure
32//! optimizations. We want to avoid that as much as possible.
33//!
34//! Thus we end up with a trade-off: The bigger the codegen units, the better
35//! LLVM's optimizer can do its work, but also the smaller the compilation time
36//! reduction we get from incremental compilation.
37//!
38//! Ideally, we would create a partitioning such that there are few big codegen
39//! units with few interdependencies between them. For now though, we use the
40//! following heuristic to determine the partitioning:
41//!
42//! - There are two codegen units for every source-level module:
43//! - One for "stable", that is non-generic, code
44//! - One for more "volatile" code, i.e., monomorphized instances of functions
45//!   defined in that module
46//!
47//! In order to see why this heuristic makes sense, let's take a look at when a
48//! codegen unit can get invalidated:
49//!
50//! 1. The most straightforward case is when the BODY of a function or global
51//! changes. Then any codegen unit containing the code for that item has to be
52//! re-compiled. Note that this includes all codegen units where the function
53//! has been inlined.
54//!
55//! 2. The next case is when the SIGNATURE of a function or global changes. In
56//! this case, all codegen units containing a REFERENCE to that item have to be
57//! re-compiled. This is a superset of case 1.
58//!
59//! 3. The final and most subtle case is when a REFERENCE to a generic function
60//! is added or removed somewhere. Even though the definition of the function
61//! might be unchanged, a new REFERENCE might introduce a new monomorphized
62//! instance of this function which has to be placed and compiled somewhere.
63//! Conversely, when removing a REFERENCE, it might have been the last one with
64//! that particular set of generic arguments and thus we have to remove it.
65//!
66//! From the above we see that just using one codegen unit per source-level
67//! module is not such a good idea, since just adding a REFERENCE to some
68//! generic item somewhere else would invalidate everything within the module
69//! containing the generic item. The heuristic above reduces this detrimental
70//! side-effect of references a little by at least not touching the non-generic
71//! code of the module.
72//!
73//! A Note on Inlining
74//! ------------------
75//! As briefly mentioned above, in order for LLVM to be able to inline a
76//! function call, the body of the function has to be available in the LLVM
77//! module where the call is made. This has a few consequences for partitioning:
78//!
79//! - The partitioning algorithm has to take care of placing functions into all
80//!   codegen units where they should be available for inlining. It also has to
81//!   decide on the correct linkage for these functions.
82//!
83//! - The partitioning algorithm has to know which functions are likely to get
84//!   inlined, so it can distribute function instantiations accordingly. Since
85//!   there is no way of knowing for sure which functions LLVM will decide to
86//!   inline in the end, we apply a heuristic here: Only functions marked with
87//!   `#[inline]` are considered for inlining by the partitioner. The current
88//!   implementation will not try to determine if a function is likely to be
89//!   inlined by looking at the functions definition.
90//!
91//! Note though that as a side-effect of creating a codegen units per
92//! source-level module, functions from the same module will be available for
93//! inlining, even when they are not marked `#[inline]`.
94
95use 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::either::Either;
102use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
103use rustc_data_structures::sync::par_join;
104use rustc_data_structures::unord::{UnordMap, UnordSet};
105use rustc_hir::attrs::lang_items::LangItem;
106use rustc_hir::attrs::{InlineAttr, Linkage};
107use rustc_hir::def::DefKind;
108use rustc_hir::def_id::{DefId, DefIdSet, LOCAL_CRATE};
109use rustc_hir::definitions::DefPathDataName;
110use rustc_middle::bug;
111use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
112use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
113use rustc_middle::mir::StatementKind;
114use rustc_middle::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, ShimKind, 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::diagnostics::{CouldntDumpMonoStats, SymbolAlreadyDefined};
129use crate::graph_checks::target_specific_checks;
130
131struct PartitioningCx<'a, 'tcx> {
132    tcx: TyCtxt<'tcx>,
133    usage_map: &'a UsageMap<'tcx>,
134}
135
136struct PlacedMonoItems<'tcx> {
137    /// The codegen units, sorted by name to make things deterministic.
138    codegen_units: Vec<CodegenUnit<'tcx>>,
139
140    internalization_candidates: UnordSet<MonoItem<'tcx>>,
141}
142
143// The output CGUs are sorted by name.
144fn partition<'tcx, I>(
145    tcx: TyCtxt<'tcx>,
146    mono_items: I,
147    usage_map: &UsageMap<'tcx>,
148) -> Vec<CodegenUnit<'tcx>>
149where
150    I: Iterator<Item = MonoItem<'tcx>>,
151{
152    let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
153
154    let cx = &PartitioningCx { tcx, usage_map };
155
156    // Place all mono items into a codegen unit. `place_mono_items` is
157    // responsible for initializing the CGU size estimates.
158    let PlacedMonoItems { mut codegen_units, internalization_candidates } = {
159        let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_items");
160        let placed = place_mono_items(cx, mono_items);
161
162        debug_dump(tcx, "PLACE", &placed.codegen_units);
163
164        placed
165    };
166
167    // Merge until we don't exceed the max CGU count.
168    // `merge_codegen_units` is responsible for updating the CGU size
169    // estimates.
170    {
171        let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus");
172        merge_codegen_units(cx, &mut codegen_units);
173        debug_dump(tcx, "MERGE", &codegen_units);
174    }
175
176    // Make as many symbols "internal" as possible, so LLVM has more freedom to
177    // optimize.
178    if !tcx.sess.link_dead_code() {
179        let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_internalize_symbols");
180        internalize_symbols(cx, &mut codegen_units, internalization_candidates);
181
182        debug_dump(tcx, "INTERNALIZE", &codegen_units);
183    }
184
185    // Mark one CGU for dead code, if necessary.
186    if tcx.sess.instrument_coverage() {
187        mark_code_coverage_dead_code_cgu(&mut codegen_units);
188    }
189
190    // Ensure CGUs are sorted by name, so that we get deterministic results.
191    if !codegen_units.is_sorted_by(|a, b| a.name().as_str() <= b.name().as_str()) {
192        let mut names = String::new();
193        for cgu in codegen_units.iter() {
194            names += &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("- {0}\n", cgu.name()))
    })format!("- {}\n", cgu.name());
195        }
196        ::rustc_middle::util::bug::bug_fmt(format_args!("unsorted CGUs:\n{0}",
        names));bug!("unsorted CGUs:\n{names}");
197    }
198
199    codegen_units
200}
201
202fn place_mono_items<'tcx, I>(cx: &PartitioningCx<'_, 'tcx>, mono_items: I) -> PlacedMonoItems<'tcx>
203where
204    I: Iterator<Item = MonoItem<'tcx>>,
205{
206    let mut codegen_units = UnordMap::default();
207    let is_incremental_build = cx.tcx.sess.opts.incremental.is_some();
208    let mut internalization_candidates = UnordSet::default();
209
210    // Determine if monomorphizations instantiated in this crate will be made
211    // available to downstream crates. This depends on whether we are in
212    // share-generics mode and whether the current crate can even have
213    // downstream crates.
214    let can_export_generics = cx.tcx.local_crate_exports_generics();
215    let always_export_generics = can_export_generics && cx.tcx.sess.opts.share_generics();
216
217    let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
218    let cgu_name_cache = &mut UnordMap::default();
219
220    for mono_item in mono_items {
221        // Handle only root (GloballyShared) items directly here. Inlined (LocalCopy) items
222        // are handled at the bottom of the loop based on reachability, with one exception.
223        // The #[lang = "start"] item is the program entrypoint, so there are no calls to it in MIR.
224        // So even if its mode is LocalCopy, we need to treat it like a root.
225        match mono_item.instantiation_mode(cx.tcx) {
226            InstantiationMode::GloballyShared { .. } => {}
227            InstantiationMode::LocalCopy => continue,
228        }
229
230        let characteristic_def_id = characteristic_def_id_of_mono_item(cx.tcx, mono_item);
231        let is_volatile = is_incremental_build && mono_item.is_generic_fn();
232
233        let cgu_name = match characteristic_def_id {
234            Some(def_id) => compute_codegen_unit_name(
235                cx.tcx,
236                cgu_name_builder,
237                def_id,
238                is_volatile,
239                cgu_name_cache,
240            ),
241            None => fallback_cgu_name(cgu_name_builder),
242        };
243
244        let cgu = codegen_units.entry(cgu_name).or_insert_with(|| CodegenUnit::new(cgu_name));
245
246        let mut can_be_internalized = true;
247        let (linkage, visibility) = mono_item_linkage_and_visibility(
248            cx.tcx,
249            &mono_item,
250            &mut can_be_internalized,
251            can_export_generics,
252            always_export_generics,
253        );
254
255        if visibility == Visibility::Hidden && can_be_internalized {
256            internalization_candidates.insert(mono_item);
257        }
258        let size_estimate = mono_item.size_estimate(cx.tcx);
259
260        cgu.items_mut()
261            .insert(mono_item, MonoItemData { inlined: false, linkage, visibility, size_estimate });
262
263        // Get all inlined items that are reachable from `mono_item` without
264        // going via another root item. This includes drop-glue, functions from
265        // external crates, and local functions the definition of which is
266        // marked with `#[inline]`.
267        let mut reachable_inlined_items = FxIndexSet::default();
268        get_reachable_inlined_items(cx.tcx, mono_item, cx.usage_map, &mut reachable_inlined_items);
269
270        // Add those inlined items. It's possible an inlined item is reachable
271        // from multiple root items within a CGU, which is fine, it just means
272        // the `insert` will be a no-op.
273        for inlined_item in reachable_inlined_items {
274            // This is a CGU-private copy.
275            cgu.items_mut().entry(inlined_item).or_insert_with(|| MonoItemData {
276                inlined: true,
277                linkage: Linkage::Internal,
278                visibility: Visibility::Default,
279                size_estimate: inlined_item.size_estimate(cx.tcx),
280            });
281        }
282    }
283
284    // Always ensure we have at least one CGU; otherwise, if we have a
285    // crate with just types (for example), we could wind up with no CGU.
286    if codegen_units.is_empty() {
287        let cgu_name = fallback_cgu_name(cgu_name_builder);
288        codegen_units.insert(cgu_name, CodegenUnit::new(cgu_name));
289    }
290
291    let mut codegen_units: Vec<_> = cx.tcx.with_stable_hashing_context(|mut hcx| {
292        codegen_units.into_items().map(|(_, cgu)| cgu).collect_sorted(&mut hcx, true)
293    });
294
295    for cgu in codegen_units.iter_mut() {
296        cgu.compute_size_estimate();
297    }
298
299    return PlacedMonoItems { codegen_units, internalization_candidates };
300
301    fn get_reachable_inlined_items<'tcx>(
302        tcx: TyCtxt<'tcx>,
303        item: MonoItem<'tcx>,
304        usage_map: &UsageMap<'tcx>,
305        visited: &mut FxIndexSet<MonoItem<'tcx>>,
306    ) {
307        usage_map.for_each_inlined_used_item(tcx, item, |inlined_item| {
308            let is_new = visited.insert(inlined_item);
309            if is_new {
310                get_reachable_inlined_items(tcx, inlined_item, usage_map, visited);
311            }
312        });
313    }
314}
315
316// This function requires the CGUs to be sorted by name on input, and ensures
317// they are sorted by name on return, for deterministic behaviour.
318fn merge_codegen_units<'tcx>(
319    cx: &PartitioningCx<'_, 'tcx>,
320    codegen_units: &mut Vec<CodegenUnit<'tcx>>,
321) {
322    if !(cx.tcx.sess.codegen_units().as_usize() >= 1) {
    ::core::panicking::panic("assertion failed: cx.tcx.sess.codegen_units().as_usize() >= 1")
};assert!(cx.tcx.sess.codegen_units().as_usize() >= 1);
323
324    // A sorted order here ensures merging is deterministic.
325    if !codegen_units.is_sorted_by(|a, b| a.name().as_str() <= b.name().as_str())
    {
    ::core::panicking::panic("assertion failed: codegen_units.is_sorted_by(|a, b| a.name().as_str() <= b.name().as_str())")
};assert!(codegen_units.is_sorted_by(|a, b| a.name().as_str() <= b.name().as_str()));
326
327    // This map keeps track of what got merged into what.
328    let mut cgu_contents: UnordMap<Symbol, Vec<Symbol>> =
329        codegen_units.iter().map(|cgu| (cgu.name(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [cgu.name()]))vec![cgu.name()])).collect();
330
331    // If N is the maximum number of CGUs, and the CGUs are sorted from largest
332    // to smallest, we repeatedly find which CGU in codegen_units[N..] has the
333    // greatest overlap of inlined items with codegen_units[N-1], merge that
334    // CGU into codegen_units[N-1], then re-sort by size and repeat.
335    //
336    // We use inlined item overlap to guide this merging because it minimizes
337    // duplication of inlined items, which makes LLVM be faster and generate
338    // better and smaller machine code.
339    //
340    // Why merge into codegen_units[N-1]? We want CGUs to have similar sizes,
341    // which means we don't want codegen_units[0..N] (the already big ones)
342    // getting any bigger, if we can avoid it. When we have more than N CGUs
343    // then at least one of the biggest N will have to grow. codegen_units[N-1]
344    // is the smallest of those, and so has the most room to grow.
345    let max_codegen_units = cx.tcx.sess.codegen_units().as_usize();
346    while codegen_units.len() > max_codegen_units {
347        // Sort small CGUs to the back.
348        codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
349
350        let cgu_dst = &codegen_units[max_codegen_units - 1];
351
352        // Find the CGU that overlaps the most with `cgu_dst`. In the case of a
353        // tie, favour the earlier (bigger) CGU.
354        let mut max_overlap = 0;
355        let mut max_overlap_i = max_codegen_units;
356        for (i, cgu_src) in codegen_units.iter().enumerate().skip(max_codegen_units) {
357            if cgu_src.size_estimate() <= max_overlap {
358                // None of the remaining overlaps can exceed `max_overlap`, so
359                // stop looking.
360                break;
361            }
362
363            let overlap = compute_inlined_overlap(cgu_dst, cgu_src);
364            if overlap > max_overlap {
365                max_overlap = overlap;
366                max_overlap_i = i;
367            }
368        }
369
370        let mut cgu_src = codegen_units.swap_remove(max_overlap_i);
371        let cgu_dst = &mut codegen_units[max_codegen_units - 1];
372
373        // Move the items from `cgu_src` to `cgu_dst`. Some of them may be
374        // duplicate inlined items, in which case the destination CGU is
375        // unaffected. Recalculate size estimates afterwards.
376        cgu_dst.items_mut().append(cgu_src.items_mut());
377        cgu_dst.compute_size_estimate();
378
379        // Record that `cgu_dst` now contains all the stuff that was in
380        // `cgu_src` before.
381        let mut consumed_cgu_names = cgu_contents.remove(&cgu_src.name()).unwrap();
382        cgu_contents.get_mut(&cgu_dst.name()).unwrap().append(&mut consumed_cgu_names);
383    }
384
385    // Having multiple CGUs can drastically speed up compilation. But for
386    // non-incremental builds, tiny CGUs slow down compilation *and* result in
387    // worse generated code. So we don't allow CGUs smaller than this (unless
388    // there is just one CGU, of course). Note that CGU sizes of 100,000+ are
389    // common in larger programs, so this isn't all that large.
390    const NON_INCR_MIN_CGU_SIZE: usize = 1800;
391
392    // Repeatedly merge the two smallest codegen units as long as: it's a
393    // non-incremental build, and the user didn't specify a CGU count, and
394    // there are multiple CGUs, and some are below the minimum size.
395    //
396    // The "didn't specify a CGU count" condition is because when an explicit
397    // count is requested we observe it as closely as possible. For example,
398    // the `compiler_builtins` crate sets `codegen-units = 10000` and it's
399    // critical they aren't merged. Also, some tests use explicit small values
400    // and likewise won't work if small CGUs are merged.
401    while cx.tcx.sess.opts.incremental.is_none()
402        && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.codegen_units() {
    CodegenUnits::Default(_) => true,
    _ => false,
}matches!(cx.tcx.sess.codegen_units(), CodegenUnits::Default(_))
403        && codegen_units.len() > 1
404        && codegen_units.iter().any(|cgu| cgu.size_estimate() < NON_INCR_MIN_CGU_SIZE)
405    {
406        // Sort small cgus to the back.
407        codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
408
409        let mut smallest = codegen_units.pop().unwrap();
410        let second_smallest = codegen_units.last_mut().unwrap();
411
412        // Move the items from `smallest` to `second_smallest`. Some of them
413        // may be duplicate inlined items, in which case the destination CGU is
414        // unaffected. Recalculate size estimates afterwards.
415        second_smallest.items_mut().append(smallest.items_mut());
416        second_smallest.compute_size_estimate();
417
418        // Don't update `cgu_contents`, that's only for incremental builds.
419    }
420
421    let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx);
422
423    // Rename the newly merged CGUs.
424    if cx.tcx.sess.opts.incremental.is_some() {
425        // If we are doing incremental compilation, we want CGU names to
426        // reflect the path of the source level module they correspond to.
427        // For CGUs that contain the code of multiple modules because of the
428        // merging done above, we use a concatenation of the names of all
429        // contained CGUs.
430        let new_cgu_names = UnordMap::from(
431            cgu_contents
432                .items()
433                // This `filter` makes sure we only update the name of CGUs that
434                // were actually modified by merging.
435                .filter(|(_, cgu_contents)| cgu_contents.len() > 1)
436                .map(|(current_cgu_name, cgu_contents)| {
437                    let mut cgu_contents: Vec<&str> =
438                        cgu_contents.iter().map(|s| s.as_str()).collect();
439
440                    // Sort the names, so things are deterministic and easy to
441                    // predict. We are sorting primitive `&str`s here so we can
442                    // use unstable sort.
443                    cgu_contents.sort_unstable();
444
445                    (*current_cgu_name, cgu_contents.join("--"))
446                }),
447        );
448
449        for cgu in codegen_units.iter_mut() {
450            if let Some(new_cgu_name) = new_cgu_names.get(&cgu.name()) {
451                let new_cgu_name = if cx.tcx.sess.opts.unstable_opts.human_readable_cgu_names {
452                    Symbol::intern(&CodegenUnit::shorten_name(new_cgu_name))
453                } else {
454                    // If we don't require CGU names to be human-readable,
455                    // we use a fixed length hash of the composite CGU name
456                    // instead.
457                    Symbol::intern(&CodegenUnit::mangle_name(new_cgu_name))
458                };
459                cgu.set_name(new_cgu_name);
460            }
461
462            // Assign symbol name to each CGU units.
463            cgu.set_symbol_name(Symbol::intern(&rustc_symbol_mangling::mangle_cgu(
464                cx.tcx,
465                LOCAL_CRATE,
466                Either::Right(cgu.name().as_str()),
467            )));
468        }
469
470        // A sorted order here ensures what follows can be deterministic.
471        codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str()));
472    } else {
473        // When compiling non-incrementally, we rename the CGUS so they have
474        // identical names except for the numeric suffix, something like
475        // `regex.f10ba03eb5ec7975-cgu.N`, where `N` varies.
476        //
477        // It is useful for debugging and profiling purposes if the resulting
478        // CGUs are sorted by name *and* reverse sorted by size. (CGU 0 is the
479        // biggest, CGU 1 is the second biggest, etc.)
480        //
481        // So first we reverse sort by size. Then we generate the names with
482        // zero-padded suffixes, which means they are automatically sorted by
483        // names. The numeric suffix width depends on the number of CGUs, which
484        // is always greater than zero:
485        // - [1,9]     CGUs: `0`, `1`, `2`, ...
486        // - [10,99]   CGUs: `00`, `01`, `02`, ...
487        // - [100,999] CGUs: `000`, `001`, `002`, ...
488        // - etc.
489        //
490        // If we didn't zero-pad the sorted-by-name order would be `XYZ-cgu.0`,
491        // `XYZ-cgu.1`, `XYZ-cgu.10`, `XYZ-cgu.11`, ..., `XYZ-cgu.2`, etc.
492        codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
493        let num_digits = codegen_units.len().ilog10() as usize + 1;
494        for (index, cgu) in codegen_units.iter_mut().enumerate() {
495            // Note: `WorkItem::short_description` depends on this name ending
496            // with `-cgu.` followed by a numeric suffix. Please keep it in
497            // sync with this code.
498            let suffix = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:01$}", index, num_digits))
    })format!("{index:0num_digits$}");
499            let numbered_codegen_unit_name =
500                cgu_name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(suffix));
501            cgu.set_name(numbered_codegen_unit_name);
502
503            cgu.set_symbol_name(Symbol::intern(&rustc_symbol_mangling::mangle_cgu(
504                cx.tcx,
505                LOCAL_CRATE,
506                Either::Left(index.try_into().unwrap()),
507            )));
508        }
509    }
510}
511
512/// Compute the combined size of all inlined items that appear in both `cgu1`
513/// and `cgu2`.
514fn compute_inlined_overlap<'tcx>(cgu1: &CodegenUnit<'tcx>, cgu2: &CodegenUnit<'tcx>) -> usize {
515    // Either order works. We pick the one that involves iterating over fewer
516    // items.
517    let (src_cgu, dst_cgu) =
518        if cgu1.items().len() <= cgu2.items().len() { (cgu1, cgu2) } else { (cgu2, cgu1) };
519
520    let mut overlap = 0;
521    for (item, data) in src_cgu.items().iter() {
522        if data.inlined && dst_cgu.items().contains_key(item) {
523            overlap += data.size_estimate;
524        }
525    }
526    overlap
527}
528
529fn internalize_symbols<'tcx>(
530    cx: &PartitioningCx<'_, 'tcx>,
531    codegen_units: &mut [CodegenUnit<'tcx>],
532    internalization_candidates: UnordSet<MonoItem<'tcx>>,
533) {
534    /// For symbol internalization, we need to know whether a symbol/mono-item
535    /// is used from outside the codegen unit it is defined in. This type is
536    /// used to keep track of that.
537    #[derive(#[automatically_derived]
impl ::core::clone::Clone for MonoItemPlacement {
    #[inline]
    fn clone(&self) -> MonoItemPlacement {
        match self {
            MonoItemPlacement::SingleCgu(__self_0) =>
                MonoItemPlacement::SingleCgu(::core::clone::Clone::clone(__self_0)),
            MonoItemPlacement::MultipleCgus =>
                MonoItemPlacement::MultipleCgus,
        }
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for MonoItemPlacement {
    #[inline]
    fn eq(&self, other: &MonoItemPlacement) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (MonoItemPlacement::SingleCgu(__self_0),
                    MonoItemPlacement::SingleCgu(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MonoItemPlacement {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for MonoItemPlacement {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MonoItemPlacement::SingleCgu(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "SingleCgu", &__self_0),
            MonoItemPlacement::MultipleCgus =>
                ::core::fmt::Formatter::write_str(f, "MultipleCgus"),
        }
    }
}Debug)]
538    enum MonoItemPlacement {
539        SingleCgu(Symbol),
540        MultipleCgus,
541    }
542
543    let mut mono_item_placements = UnordMap::default();
544    let single_codegen_unit = codegen_units.len() == 1;
545
546    if !single_codegen_unit {
547        for cgu in codegen_units.iter() {
548            for item in cgu.items().keys() {
549                // If there is more than one codegen unit, we need to keep track
550                // in which codegen units each monomorphization is placed.
551                match mono_item_placements.entry(*item) {
552                    Entry::Occupied(e) => {
553                        let placement = e.into_mut();
554                        if true {
    if !match *placement {
                MonoItemPlacement::SingleCgu(cgu_name) =>
                    cgu_name != cgu.name(),
                MonoItemPlacement::MultipleCgus => true,
            } {
        ::core::panicking::panic("assertion failed: match *placement {\n    MonoItemPlacement::SingleCgu(cgu_name) => cgu_name != cgu.name(),\n    MonoItemPlacement::MultipleCgus => true,\n}")
    };
};debug_assert!(match *placement {
555                            MonoItemPlacement::SingleCgu(cgu_name) => cgu_name != cgu.name(),
556                            MonoItemPlacement::MultipleCgus => true,
557                        });
558                        *placement = MonoItemPlacement::MultipleCgus;
559                    }
560                    Entry::Vacant(e) => {
561                        e.insert(MonoItemPlacement::SingleCgu(cgu.name()));
562                    }
563                }
564            }
565        }
566    }
567
568    // For each internalization candidates in each codegen unit, check if it is
569    // used from outside its defining codegen unit.
570    for cgu in codegen_units {
571        let home_cgu = MonoItemPlacement::SingleCgu(cgu.name());
572
573        for (item, data) in cgu.items_mut() {
574            if !internalization_candidates.contains(item) {
575                // This item is no candidate for internalizing, so skip it.
576                continue;
577            }
578
579            if !single_codegen_unit {
580                if true {
    {
        match (&mono_item_placements[item], &home_cgu) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(mono_item_placements[item], home_cgu);
581
582                if cx
583                    .usage_map
584                    .get_user_items(*item)
585                    .iter()
586                    .filter_map(|user_item| {
587                        // Some user mono items might not have been
588                        // instantiated. We can safely ignore those.
589                        mono_item_placements.get(user_item)
590                    })
591                    .any(|placement| *placement != home_cgu)
592                {
593                    // Found a user from another CGU, so skip to the next item
594                    // without marking this one as internal.
595                    continue;
596                }
597            }
598
599            // When LTO inlines the caller of a naked function, it will attempt but fail to make the
600            // naked function symbol visible. To ensure that LTO works correctly, do not default
601            // naked functions to internal linkage and default visibility.
602            if let MonoItem::Fn(instance) = item {
603                let flags = cx.tcx.codegen_instance_attrs(instance.def).flags;
604                if flags.contains(CodegenFnAttrFlags::NAKED) {
605                    continue;
606                }
607            }
608
609            // If we got here, we did not find any uses from other CGUs, so
610            // it's fine to make this monomorphization internal.
611            data.linkage = Linkage::Internal;
612            data.visibility = Visibility::Default;
613        }
614    }
615}
616
617fn mark_code_coverage_dead_code_cgu<'tcx>(codegen_units: &mut [CodegenUnit<'tcx>]) {
618    if !!codegen_units.is_empty() {
    ::core::panicking::panic("assertion failed: !codegen_units.is_empty()")
};assert!(!codegen_units.is_empty());
619
620    // Find the smallest CGU that has exported symbols and put the dead
621    // function stubs in that CGU. We look for exported symbols to increase
622    // the likelihood the linker won't throw away the dead functions.
623    // FIXME(#92165): In order to truly resolve this, we need to make sure
624    // the object file (CGU) containing the dead function stubs is included
625    // in the final binary. This will probably require forcing these
626    // function symbols to be included via `-u` or `/include` linker args.
627    let dead_code_cgu = codegen_units
628        .iter_mut()
629        .filter(|cgu| cgu.items().iter().any(|(_, data)| data.linkage == Linkage::External))
630        .min_by_key(|cgu| cgu.size_estimate());
631
632    // If there are no CGUs that have externally linked items, then we just
633    // pick the first CGU as a fallback.
634    let dead_code_cgu = if let Some(cgu) = dead_code_cgu { cgu } else { &mut codegen_units[0] };
635
636    dead_code_cgu.make_code_coverage_dead_code_cgu();
637}
638
639fn characteristic_def_id_of_mono_item<'tcx>(
640    tcx: TyCtxt<'tcx>,
641    mono_item: MonoItem<'tcx>,
642) -> Option<DefId> {
643    match mono_item {
644        MonoItem::Fn(instance) => {
645            let def_id = match instance.def {
646                ty::InstanceKind::Item(def) => def,
647                ty::InstanceKind::Intrinsic(..)
648                | ty::InstanceKind::LlvmIntrinsic(..)
649                | ty::InstanceKind::Virtual(..)
650                | ty::InstanceKind::Shim(ty::ShimKind::VTable(..))
651                | ty::InstanceKind::Shim(ty::ShimKind::Reify(..))
652                | ty::InstanceKind::Shim(ty::ShimKind::FnPtr(..))
653                | ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. })
654                | ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure { .. })
655                | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(..))
656                | ty::InstanceKind::Shim(ty::ShimKind::Clone(..))
657                | ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..))
658                | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr(..))
659                | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(..))
660                | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(..))
661                | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(..)) => return None,
662            };
663
664            // If this is a method, we want to put it into the same module as
665            // its self-type. If the self-type does not provide a characteristic
666            // DefId, we use the location of the impl after all.
667
668            let assoc_parent = tcx.assoc_parent(def_id);
669
670            if let Some((_, DefKind::Trait)) = assoc_parent {
671                let self_ty = instance.args.type_at(0);
672                // This is a default implementation of a trait method.
673                return characteristic_def_id_of_type(self_ty).or(Some(def_id));
674            }
675
676            if let Some((impl_def_id, DefKind::Impl { of_trait })) = assoc_parent {
677                if of_trait
678                    && tcx.sess.opts.incremental.is_some()
679                    && tcx.is_lang_item(tcx.impl_trait_id(impl_def_id), LangItem::Drop)
680                {
681                    // Put `Drop::drop` into the same cgu as `drop_glue`
682                    // since `drop_glue` is the only thing that can call it.
683                    return None;
684                }
685
686                // This is a method within an impl, find out what the self-type is:
687                let impl_self_ty = tcx.instantiate_and_normalize_erasing_regions(
688                    instance.args,
689                    ty::TypingEnv::fully_monomorphized(),
690                    tcx.type_of(impl_def_id),
691                );
692                if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
693                    return Some(def_id);
694                }
695            }
696
697            Some(def_id)
698        }
699        MonoItem::Static(def_id) => Some(def_id),
700        MonoItem::GlobalAsm(item_id) => Some(item_id.owner_id.to_def_id()),
701    }
702}
703
704fn compute_codegen_unit_name(
705    tcx: TyCtxt<'_>,
706    name_builder: &mut CodegenUnitNameBuilder<'_>,
707    def_id: DefId,
708    volatile: bool,
709    cache: &mut CguNameCache,
710) -> Symbol {
711    // Find the innermost module that is not nested within a function.
712    let mut current_def_id = def_id;
713    let mut cgu_def_id = None;
714    // Walk backwards from the item we want to find the module for.
715    loop {
716        if current_def_id.is_crate_root() {
717            if cgu_def_id.is_none() {
718                // If we have not found a module yet, take the crate root.
719                cgu_def_id = Some(def_id.krate.as_def_id());
720            }
721            break;
722        } else if tcx.def_kind(current_def_id) == DefKind::Mod {
723            if cgu_def_id.is_none() {
724                cgu_def_id = Some(current_def_id);
725            }
726        } else {
727            // If we encounter something that is not a module, throw away
728            // any module that we've found so far because we now know that
729            // it is nested within something else.
730            cgu_def_id = None;
731        }
732
733        current_def_id = tcx.parent(current_def_id);
734    }
735
736    let cgu_def_id = cgu_def_id.unwrap();
737
738    *cache.entry((cgu_def_id, volatile)).or_insert_with(|| {
739        let def_path = tcx.def_path(cgu_def_id);
740
741        let components = def_path.data.iter().map(|part| match part.data.name() {
742            DefPathDataName::Named(name) => name,
743            DefPathDataName::Anon { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
744        });
745
746        let volatile_suffix = volatile.then_some("volatile");
747
748        name_builder.build_cgu_name(def_path.krate, components, volatile_suffix)
749    })
750}
751
752// Anything we can't find a proper codegen unit for goes into this.
753fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_>) -> Symbol {
754    name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu"))
755}
756
757fn mono_item_linkage_and_visibility<'tcx>(
758    tcx: TyCtxt<'tcx>,
759    mono_item: &MonoItem<'tcx>,
760    can_be_internalized: &mut bool,
761    can_export_generics: bool,
762    always_export_generics: bool,
763) -> (Linkage, Visibility) {
764    if let Some(explicit_linkage) = mono_item.explicit_linkage(tcx) {
765        return (explicit_linkage, Visibility::Default);
766    }
767    let vis = mono_item_visibility(
768        tcx,
769        mono_item,
770        can_be_internalized,
771        can_export_generics,
772        always_export_generics,
773    );
774    (Linkage::External, vis)
775}
776
777type CguNameCache = UnordMap<(DefId, bool), Symbol>;
778
779fn static_visibility<'tcx>(
780    tcx: TyCtxt<'tcx>,
781    can_be_internalized: &mut bool,
782    def_id: DefId,
783) -> Visibility {
784    if tcx.is_reachable_non_generic(def_id) {
785        *can_be_internalized = false;
786        default_visibility(tcx, def_id, false)
787    } else {
788        if tcx.def_kind(def_id).has_codegen_attrs() {
789            // Prevent EII and `rustc_std_internal_symbol` statics being internalized.
790            let attrs = tcx.codegen_fn_attrs(def_id);
791            if attrs.flags.intersects(
792                CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
793                    | CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM,
794            ) {
795                *can_be_internalized = false;
796            }
797        }
798
799        Visibility::Hidden
800    }
801}
802
803fn mono_item_visibility<'tcx>(
804    tcx: TyCtxt<'tcx>,
805    mono_item: &MonoItem<'tcx>,
806    can_be_internalized: &mut bool,
807    can_export_generics: bool,
808    always_export_generics: bool,
809) -> Visibility {
810    let instance = match mono_item {
811        // This is pretty complicated; see below.
812        MonoItem::Fn(instance) => instance,
813
814        // Misc handling for generics and such, but otherwise:
815        MonoItem::Static(def_id) => return static_visibility(tcx, can_be_internalized, *def_id),
816        MonoItem::GlobalAsm(item_id) => {
817            return static_visibility(tcx, can_be_internalized, item_id.owner_id.to_def_id());
818        }
819    };
820
821    let def_id = match instance.def {
822        InstanceKind::Item(def_id)
823        | InstanceKind::Shim(ShimKind::DropGlue(def_id, Some(_)))
824        | InstanceKind::Shim(ShimKind::FutureDropPoll(def_id, _, _))
825        | InstanceKind::Shim(ShimKind::AsyncDropGlue(def_id, _))
826        | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(def_id, _)) => def_id,
827
828        // We match the visibility of statics here
829        InstanceKind::Shim(ShimKind::ThreadLocal(def_id)) => {
830            return static_visibility(tcx, can_be_internalized, def_id);
831        }
832
833        // These are all compiler glue and such, never exported, always hidden.
834        InstanceKind::Shim(ShimKind::VTable(..))
835        | InstanceKind::Shim(ShimKind::Reify(..))
836        | InstanceKind::Shim(ShimKind::FnPtr(..))
837        | InstanceKind::Virtual(..)
838        | InstanceKind::Intrinsic(..)
839        | InstanceKind::LlvmIntrinsic(..)
840        | InstanceKind::Shim(ShimKind::ClosureOnce { .. })
841        | InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure { .. })
842        | InstanceKind::Shim(ShimKind::DropGlue(..))
843        | InstanceKind::Shim(ShimKind::Clone(..))
844        | InstanceKind::Shim(ShimKind::FnPtrAddr(..)) => return Visibility::Hidden,
845    };
846
847    let attrs = tcx.codegen_fn_attrs(def_id);
848    if attrs.flags.intersects(CodegenFnAttrFlags::OFFLOAD_KERNEL) {
849        *can_be_internalized = false;
850        return default_visibility(
851            tcx,
852            def_id,
853            instance.args.non_erasable_generics().next().is_some(),
854        );
855    }
856
857    // Both the `start_fn` lang item and `main` itself should not be exported,
858    // so we give them with `Hidden` visibility but these symbols are
859    // only referenced from the actual `main` symbol which we unfortunately
860    // don't know anything about during partitioning/collection. As a result we
861    // forcibly keep this symbol out of the `internalization_candidates` set.
862    //
863    // FIXME: eventually we don't want to always force this symbol to have
864    //        hidden visibility, it should indeed be a candidate for
865    //        internalization, but we have to understand that it's referenced
866    //        from the `main` symbol we'll generate later.
867    //
868    //        This may be fixable with a new `InstanceKind` perhaps? Unsure!
869    if tcx.is_entrypoint(def_id) {
870        *can_be_internalized = false;
871        return Visibility::Hidden;
872    }
873
874    let is_generic = instance.args.non_erasable_generics().next().is_some();
875
876    // Upstream `DefId` instances get different handling than local ones.
877    let Some(def_id) = def_id.as_local() else {
878        return if is_generic
879            && (always_export_generics
880                || (can_export_generics
881                    && tcx.codegen_fn_attrs(def_id).inline == InlineAttr::Never))
882        {
883            // If it is an upstream monomorphization and we export generics, we must make
884            // it available to downstream crates.
885            *can_be_internalized = false;
886            default_visibility(tcx, def_id, true)
887        } else {
888            Visibility::Hidden
889        };
890    };
891
892    if is_generic {
893        if always_export_generics
894            || (can_export_generics && tcx.codegen_fn_attrs(def_id).inline == InlineAttr::Never)
895        {
896            if tcx.is_unreachable_local_definition(def_id) {
897                // This instance cannot be used from another crate.
898                Visibility::Hidden
899            } else {
900                // This instance might be useful in a downstream crate.
901                *can_be_internalized = false;
902                default_visibility(tcx, def_id.to_def_id(), true)
903            }
904        } else {
905            // We are not exporting generics or the definition is not reachable
906            // for downstream crates, we can internalize its instantiations.
907            Visibility::Hidden
908        }
909    } else {
910        // If this isn't a generic function then we mark this a `Default` if
911        // this is a reachable item, meaning that it's a symbol other crates may
912        // use when they link to us.
913        if tcx.is_reachable_non_generic(def_id.to_def_id()) {
914            *can_be_internalized = false;
915            if true {
    if !!is_generic {
        ::core::panicking::panic("assertion failed: !is_generic")
    };
};debug_assert!(!is_generic);
916            return default_visibility(tcx, def_id.to_def_id(), false);
917        }
918
919        // If this isn't reachable then we're gonna tag this with `Hidden`
920        // visibility. In some situations though we'll want to prevent this
921        // symbol from being internalized.
922        //
923        // There's three categories of items here:
924        //
925        // * First is weak lang items. These are basically mechanisms for
926        //   libcore to forward-reference symbols defined later in crates like
927        //   the standard library or `#[panic_handler]` definitions. The
928        //   definition of these weak lang items needs to be referenceable by
929        //   libcore, so we're no longer a candidate for internalization.
930        //   Removal of these functions can't be done by LLVM but rather must be
931        //   done by the linker as it's a non-local decision.
932        //
933        // * Second is "std internal symbols". Currently this is primarily used
934        //   for allocator symbols. Allocators are a little weird in their
935        //   implementation, but the idea is that the compiler, at the last
936        //   minute, defines an allocator with an injected object file. The
937        //   `alloc` crate references these symbols (`__rust_alloc`) and the
938        //   definition doesn't get hooked up until a linked crate artifact is
939        //   generated.
940        //
941        //   The symbols synthesized by the compiler (`__rust_alloc`) are thin
942        //   veneers around the actual implementation, some other symbol which
943        //   implements the same ABI. These symbols (things like `__rg_alloc`,
944        //   `__rdl_alloc`, `__rde_alloc`, etc), are all tagged with "std
945        //   internal symbols".
946        //
947        //   The std-internal symbols here **should not show up in a dll as an
948        //   exported interface**, so they return `false` from
949        //   `is_reachable_non_generic` above and we'll give them `Hidden`
950        //   visibility below. Like the weak lang items, though, we can't let
951        //   LLVM internalize them as this decision is left up to the linker to
952        //   omit them, so prevent them from being internalized.
953        //
954        // * Externally implementable items. They work (in this case) pretty much the same as
955        //   RUSTC_STD_INTERNAL_SYMBOL in that their implementation is also chosen later in
956        //   the compilation process and we can't let them be internalized and they can't
957        //   show up as an external interface.
958        let attrs = tcx.codegen_fn_attrs(def_id);
959        if attrs.flags.intersects(
960            CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
961                | CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM,
962        ) {
963            *can_be_internalized = false;
964        }
965
966        Visibility::Hidden
967    }
968}
969
970fn default_visibility(tcx: TyCtxt<'_>, id: DefId, is_generic: bool) -> Visibility {
971    // Fast-path to avoid expensive query call below
972    if tcx.sess.default_visibility() == SymbolVisibility::Interposable {
973        return Visibility::Default;
974    }
975
976    let export_level = if is_generic {
977        // Generic functions never have export-level C.
978        SymbolExportLevel::Rust
979    } else {
980        match tcx.reachable_non_generics(id.krate).get(&id) {
981            Some(SymbolExportInfo { level: SymbolExportLevel::C, .. }) => SymbolExportLevel::C,
982            _ => SymbolExportLevel::Rust,
983        }
984    };
985
986    match export_level {
987        // C-export level items remain at `Default` to allow C code to
988        // access and interpose them.
989        SymbolExportLevel::C => Visibility::Default,
990
991        // For all other symbols, `default_visibility` determines which visibility to use.
992        SymbolExportLevel::Rust => tcx.sess.default_visibility().into(),
993    }
994}
995
996fn debug_dump<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx>, label: &str, cgus: &[CodegenUnit<'tcx>]) {
997    let dump = move || {
998        use std::fmt::Write;
999
1000        let mut num_cgus = 0;
1001        let mut all_cgu_sizes = Vec::new();
1002
1003        // Note: every unique root item is placed exactly once, so the number
1004        // of unique root items always equals the number of placed root items.
1005        //
1006        // Also, unreached inlined items won't be counted here. This is fine.
1007
1008        let mut inlined_items = UnordSet::default();
1009
1010        let mut root_items = 0;
1011        let mut unique_inlined_items = 0;
1012        let mut placed_inlined_items = 0;
1013
1014        let mut root_size = 0;
1015        let mut unique_inlined_size = 0;
1016        let mut placed_inlined_size = 0;
1017
1018        for cgu in cgus.iter() {
1019            num_cgus += 1;
1020            all_cgu_sizes.push(cgu.size_estimate());
1021
1022            for (item, data) in cgu.items() {
1023                if !data.inlined {
1024                    root_items += 1;
1025                    root_size += data.size_estimate;
1026                } else {
1027                    if inlined_items.insert(item) {
1028                        unique_inlined_items += 1;
1029                        unique_inlined_size += data.size_estimate;
1030                    }
1031                    placed_inlined_items += 1;
1032                    placed_inlined_size += data.size_estimate;
1033                }
1034            }
1035        }
1036
1037        all_cgu_sizes.sort_unstable_by_key(|&n| cmp::Reverse(n));
1038
1039        let unique_items = root_items + unique_inlined_items;
1040        let placed_items = root_items + placed_inlined_items;
1041        let items_ratio = placed_items as f64 / unique_items as f64;
1042
1043        let unique_size = root_size + unique_inlined_size;
1044        let placed_size = root_size + placed_inlined_size;
1045        let size_ratio = placed_size as f64 / unique_size as f64;
1046
1047        let mean_cgu_size = placed_size as f64 / num_cgus as f64;
1048
1049        {
    match (&placed_size, &all_cgu_sizes.iter().sum::<usize>()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(placed_size, all_cgu_sizes.iter().sum::<usize>());
1050
1051        let s = &mut String::new();
1052        let _ = s.write_fmt(format_args!("{0}\n", label))writeln!(s, "{label}");
1053        let _ = s.write_fmt(format_args!("- unique items: {1} ({2} root + {3} inlined), unique size: {4} ({5} root + {6} inlined)\n- placed items: {7} ({2} root + {8} inlined), placed size: {9} ({5} root + {10} inlined)\n- placed/unique items ratio: {11:.2}, placed/unique size ratio: {12:.2}\n- CGUs: {13}, mean size: {14:.1}, sizes: {0}\n",
        list(&all_cgu_sizes), unique_items, root_items, unique_inlined_items,
        unique_size, root_size, unique_inlined_size, placed_items,
        placed_inlined_items, placed_size, placed_inlined_size, items_ratio,
        size_ratio, num_cgus, mean_cgu_size))writeln!(
1054            s,
1055            "- unique items: {unique_items} ({root_items} root + {unique_inlined_items} inlined), \
1056               unique size: {unique_size} ({root_size} root + {unique_inlined_size} inlined)\n\
1057             - placed items: {placed_items} ({root_items} root + {placed_inlined_items} inlined), \
1058               placed size: {placed_size} ({root_size} root + {placed_inlined_size} inlined)\n\
1059             - placed/unique items ratio: {items_ratio:.2}, \
1060               placed/unique size ratio: {size_ratio:.2}\n\
1061             - CGUs: {num_cgus}, mean size: {mean_cgu_size:.1}, sizes: {}",
1062            list(&all_cgu_sizes),
1063        );
1064        let _ = s.write_fmt(format_args!("\n"))writeln!(s);
1065
1066        for (i, cgu) in cgus.iter().enumerate() {
1067            let name = cgu.name();
1068            let size = cgu.size_estimate();
1069            let num_items = cgu.items().len();
1070            let mean_size = size as f64 / num_items as f64;
1071
1072            let mut placed_item_sizes: Vec<_> =
1073                cgu.items().values().map(|data| data.size_estimate).collect();
1074            placed_item_sizes.sort_unstable_by_key(|&n| cmp::Reverse(n));
1075            let sizes = list(&placed_item_sizes);
1076
1077            let _ = s.write_fmt(format_args!("- CGU[{0}]\n", i))writeln!(s, "- CGU[{i}]");
1078            let _ = s.write_fmt(format_args!("  - {0}, size: {1}\n", name, size))writeln!(s, "  - {name}, size: {size}");
1079            let _ =
1080                s.write_fmt(format_args!("  - items: {0}, mean size: {1:.1}, sizes: {2}\n",
        num_items, mean_size, sizes))writeln!(s, "  - items: {num_items}, mean size: {mean_size:.1}, sizes: {sizes}",);
1081
1082            for (item, data) in cgu.items_in_deterministic_order(tcx) {
1083                let linkage = data.linkage;
1084                let symbol_name = item.symbol_name(tcx).name;
1085                let symbol_hash_start = symbol_name.rfind('h');
1086                let symbol_hash = symbol_hash_start.map_or("<no hash>", |i| &symbol_name[i..]);
1087                let kind = if !data.inlined { "root" } else { "inlined" };
1088                let size = data.size_estimate;
1089                let _ = {
    let _guard = NoTrimmedGuard::new();
    s.write_fmt(format_args!("  - {0} [{1:?}] [{2}] ({3}, size: {4})\n", item,
            linkage, symbol_hash, kind, size))
}with_no_trimmed_paths!(writeln!(
1090                    s,
1091                    "  - {item} [{linkage:?}] [{symbol_hash}] ({kind}, size: {size})"
1092                ));
1093            }
1094
1095            let _ = s.write_fmt(format_args!("\n"))writeln!(s);
1096        }
1097
1098        return std::mem::take(s);
1099
1100        // Converts a slice to a string, capturing repetitions to save space.
1101        // E.g. `[4, 4, 4, 3, 2, 1, 1, 1, 1, 1]` -> "[4 (x3), 3, 2, 1 (x5)]".
1102        fn list(ns: &[usize]) -> String {
1103            let mut v = Vec::new();
1104            if ns.is_empty() {
1105                return "[]".to_string();
1106            }
1107
1108            let mut elem = |curr, curr_count| {
1109                if curr_count == 1 {
1110                    v.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", curr))
    })format!("{curr}"));
1111                } else {
1112                    v.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} (x{1})", curr, curr_count))
    })format!("{curr} (x{curr_count})"));
1113                }
1114            };
1115
1116            let mut curr = ns[0];
1117            let mut curr_count = 1;
1118
1119            for &n in &ns[1..] {
1120                if n != curr {
1121                    elem(curr, curr_count);
1122                    curr = n;
1123                    curr_count = 1;
1124                } else {
1125                    curr_count += 1;
1126                }
1127            }
1128            elem(curr, curr_count);
1129
1130            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("[{0}]", v.join(", ")))
    })format!("[{}]", v.join(", "))
1131        }
1132    };
1133
1134    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/partitioning.rs:1134",
                        "rustc_monomorphize::partitioning", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/partitioning.rs"),
                        ::tracing_core::__macro_support::Option::Some(1134u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::partitioning"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0}",
                                                    dump()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("{}", dump());
1135}
1136
1137#[inline(never)] // give this a place in the profiler
1138fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, mono_items: I)
1139where
1140    I: Iterator<Item = &'a MonoItem<'tcx>>,
1141    'tcx: 'a,
1142{
1143    let _prof_timer = tcx.prof.generic_activity("assert_symbols_are_distinct");
1144
1145    let mut symbols: Vec<_> =
1146        mono_items.map(|mono_item| (mono_item, mono_item.symbol_name(tcx))).collect();
1147
1148    symbols.sort_by_key(|sym| sym.1);
1149
1150    for &[(mono_item1, ref sym1), (mono_item2, ref sym2)] in symbols.array_windows() {
1151        if sym1 == sym2 {
1152            let span1 = mono_item1.local_span(tcx);
1153            let span2 = mono_item2.local_span(tcx);
1154
1155            // Deterministically select one of the spans for error reporting
1156            let span = match (span1, span2) {
1157                (Some(span1), Some(span2)) => {
1158                    Some(if span1.lo().0 > span2.lo().0 { span1 } else { span2 })
1159                }
1160                (span1, span2) => span1.or(span2),
1161            };
1162
1163            tcx.dcx().emit_fatal(SymbolAlreadyDefined { span, symbol: sym1.to_string() });
1164        }
1165    }
1166}
1167
1168fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> MonoItemPartitions<'_> {
1169    let collection_strategy = if tcx.sess.link_dead_code() {
1170        MonoItemCollectionStrategy::Eager
1171    } else {
1172        MonoItemCollectionStrategy::Lazy
1173    };
1174
1175    let (items, usage_map) = collector::collect_crate_mono_items(tcx, collection_strategy);
1176    // Perform checks that need to operate on the entire mono item graph
1177    target_specific_checks(tcx, &items, &usage_map);
1178
1179    // If there was an error during collection (e.g. from one of the constants we evaluated),
1180    // then we stop here. This way codegen does not have to worry about failing constants.
1181    // (codegen relies on this and ICEs will happen if this is violated.)
1182    tcx.dcx().abort_if_errors();
1183
1184    let (codegen_units, _) = tcx.sess.time("partition_and_assert_distinct_symbols", || {
1185        par_join(
1186            || {
1187                let mut codegen_units = partition(tcx, items.iter().copied(), &usage_map);
1188                codegen_units[0].make_primary();
1189                &*tcx.arena.alloc_from_iter(codegen_units)
1190            },
1191            || assert_symbols_are_distinct(tcx, items.iter()),
1192        )
1193    });
1194
1195    if tcx.prof.enabled() {
1196        // Record CGU size estimates for self-profiling.
1197        for cgu in codegen_units {
1198            tcx.prof.artifact_size(
1199                "codegen_unit_size_estimate",
1200                cgu.name().as_str(),
1201                cgu.size_estimate() as u64,
1202            );
1203        }
1204    }
1205
1206    let mono_items: DefIdSet = items
1207        .iter()
1208        .filter_map(|mono_item| match *mono_item {
1209            MonoItem::Fn(ref instance) => Some(instance.def_id()),
1210            MonoItem::Static(def_id) => Some(def_id),
1211            _ => None,
1212        })
1213        .collect();
1214
1215    // Output monomorphization stats per def_id
1216    if let SwitchWithOptPath::Enabled(ref path) = tcx.sess.opts.unstable_opts.dump_mono_stats
1217        && let Err(err) =
1218            dump_mono_items_stats(tcx, codegen_units, path, tcx.crate_name(LOCAL_CRATE))
1219    {
1220        tcx.dcx().emit_fatal(CouldntDumpMonoStats { error: err.to_string() });
1221    }
1222
1223    if tcx.sess.opts.unstable_opts.print_mono_items {
1224        let mut item_to_cgus: UnordMap<_, Vec<_>> = Default::default();
1225
1226        for cgu in codegen_units {
1227            for (&mono_item, &data) in cgu.items() {
1228                item_to_cgus.entry(mono_item).or_default().push((cgu.name(), data.linkage));
1229            }
1230        }
1231
1232        let mut item_keys: Vec<_> = items
1233            .iter()
1234            .map(|i| {
1235                let mut output = { let _guard = NoTrimmedGuard::new(); i.to_string() }with_no_trimmed_paths!(i.to_string());
1236                output.push_str(" @@");
1237                let mut empty = Vec::new();
1238                let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1239                cgus.sort_by_key(|(name, _)| *name);
1240                cgus.dedup();
1241                for &(ref cgu_name, linkage) in cgus.iter() {
1242                    output.push(' ');
1243                    output.push_str(cgu_name.as_str());
1244
1245                    let linkage_abbrev = match linkage {
1246                        Linkage::External => "External",
1247                        Linkage::AvailableExternally => "Available",
1248                        Linkage::LinkOnceAny => "OnceAny",
1249                        Linkage::LinkOnceODR => "OnceODR",
1250                        Linkage::WeakAny => "WeakAny",
1251                        Linkage::WeakODR => "WeakODR",
1252                        Linkage::Internal => "Internal",
1253                        Linkage::ExternalWeak => "ExternalWeak",
1254                        Linkage::Common => "Common",
1255                    };
1256
1257                    output.push('[');
1258                    output.push_str(linkage_abbrev);
1259                    output.push(']');
1260                }
1261                output
1262            })
1263            .collect();
1264
1265        item_keys.sort();
1266
1267        for item in item_keys {
1268            { ::std::io::_print(format_args!("MONO_ITEM {0}\n", item)); };println!("MONO_ITEM {item}");
1269        }
1270    }
1271
1272    MonoItemPartitions { all_mono_items: tcx.arena.alloc(mono_items), codegen_units }
1273}
1274
1275/// Outputs stats about instantiation counts and estimated size, per `MonoItem`'s
1276/// def, to a file in the given output directory.
1277fn dump_mono_items_stats<'tcx>(
1278    tcx: TyCtxt<'tcx>,
1279    codegen_units: &[CodegenUnit<'tcx>],
1280    output_directory: &Option<PathBuf>,
1281    crate_name: Symbol,
1282) -> Result<(), Box<dyn std::error::Error>> {
1283    let output_directory = if let Some(directory) = output_directory {
1284        fs::create_dir_all(directory)?;
1285        directory
1286    } else {
1287        Path::new(".")
1288    };
1289
1290    let format = tcx.sess.opts.unstable_opts.dump_mono_stats_format;
1291    let ext = format.extension();
1292    let filename = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.mono_items.{1}", crate_name,
                ext))
    })format!("{crate_name}.mono_items.{ext}");
1293    let output_path = output_directory.join(&filename);
1294    let mut file = File::create_buffered(&output_path)?;
1295
1296    // Gather instantiated mono items grouped by def_id
1297    let mut items_per_def_id: FxIndexMap<_, Vec<_>> = Default::default();
1298    for cgu in codegen_units {
1299        cgu.items()
1300            .keys()
1301            // Avoid variable-sized compiler-generated shims
1302            .filter(|mono_item| mono_item.is_user_defined())
1303            .for_each(|mono_item| {
1304                items_per_def_id.entry(mono_item.def_id()).or_default().push(mono_item);
1305            });
1306    }
1307
1308    #[derive(#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
    {
        #[allow(unused_extern_crates, clippy :: useless_attribute)]
        extern crate serde as _serde;
        ;
        #[automatically_derived]
        impl _serde::Serialize for MonoItem {
            fn serialize<__S>(&self, __serializer: __S)
                -> _serde::__private228::Result<__S::Ok, __S::Error> where
                __S: _serde::Serializer {
                let mut __serde_state =
                    _serde::Serializer::serialize_struct(__serializer,
                            "MonoItem", false as usize + 1 + 1 + 1 + 1)?;
                _serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
                        "name", &self.name)?;
                _serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
                        "instantiation_count", &self.instantiation_count)?;
                _serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
                        "size_estimate", &self.size_estimate)?;
                _serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
                        "total_estimate", &self.total_estimate)?;
                _serde::ser::SerializeStruct::end(__serde_state)
            }
        }
    };serde::Serialize)]
1309    struct MonoItem {
1310        name: String,
1311        instantiation_count: usize,
1312        size_estimate: usize,
1313        total_estimate: usize,
1314    }
1315
1316    // Output stats sorted by total instantiated size, from heaviest to lightest
1317    let mut stats: Vec<_> = items_per_def_id
1318        .into_iter()
1319        .map(|(def_id, items)| {
1320            let name = { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(def_id) }with_no_trimmed_paths!(tcx.def_path_str(def_id));
1321            let instantiation_count = items.len();
1322            let size_estimate = items[0].size_estimate(tcx);
1323            let total_estimate = instantiation_count * size_estimate;
1324            MonoItem { name, instantiation_count, size_estimate, total_estimate }
1325        })
1326        .collect();
1327    stats.sort_unstable_by_key(|item| cmp::Reverse(item.total_estimate));
1328
1329    if !stats.is_empty() {
1330        match format {
1331            DumpMonoStatsFormat::Json => serde_json::to_writer(file, &stats)?,
1332            DumpMonoStatsFormat::Markdown => {
1333                file.write_fmt(format_args!("| Item | Instantiation count | Estimated Cost Per Instantiation | Total Estimated Cost |\n"))writeln!(
1334                    file,
1335                    "| Item | Instantiation count | Estimated Cost Per Instantiation | Total Estimated Cost |"
1336                )?;
1337                file.write_fmt(format_args!("| --- | ---: | ---: | ---: |\n"))writeln!(file, "| --- | ---: | ---: | ---: |")?;
1338
1339                for MonoItem { name, instantiation_count, size_estimate, total_estimate } in stats {
1340                    file.write_fmt(format_args!("| `{0}` | {1} | {2} | {3} |\n", name,
        instantiation_count, size_estimate, total_estimate))writeln!(
1341                        file,
1342                        "| `{name}` | {instantiation_count} | {size_estimate} | {total_estimate} |"
1343                    )?;
1344                }
1345            }
1346        }
1347    }
1348
1349    Ok(())
1350}
1351
1352pub(crate) fn provide(providers: &mut Providers) {
1353    providers.queries.collect_and_partition_mono_items = collect_and_partition_mono_items;
1354
1355    providers.queries.is_codegened_item =
1356        |tcx, def_id| tcx.collect_and_partition_mono_items(()).all_mono_items.contains(&def_id);
1357
1358    providers.queries.codegen_unit = |tcx, name| {
1359        tcx.collect_and_partition_mono_items(())
1360            .codegen_units
1361            .iter()
1362            .find(|cgu| cgu.name() == name)
1363            .unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("failed to find cgu with name {0:?}",
            name));
}panic!("failed to find cgu with name {name:?}"))
1364    };
1365
1366    providers.queries.size_estimate = |tcx, instance| {
1367        match instance.def {
1368            // "Normal" functions size estimate: the number of
1369            // statements, plus one for the terminator.
1370            InstanceKind::Item(..)
1371            | InstanceKind::Shim(ShimKind::DropGlue(..))
1372            | InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(..)) => {
1373                let mir = tcx.instance_mir(instance.def);
1374                mir.basic_blocks
1375                    .iter()
1376                    .map(|bb| {
1377                        bb.statements
1378                            .iter()
1379                            .filter_map(|stmt| match stmt.kind {
1380                                StatementKind::StorageLive(_) | StatementKind::StorageDead(_) => {
1381                                    None
1382                                }
1383                                _ => Some(stmt),
1384                            })
1385                            .count()
1386                            + 1
1387                    })
1388                    .sum()
1389            }
1390            // Other compiler-generated shims size estimate: 1
1391            _ => 1,
1392        }
1393    };
1394
1395    collector::provide(providers);
1396}