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