rustc_middle/mir/mono.rs
1use std::fmt;
2use std::hash::Hash;
3
4use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
5use rustc_attr_parsing::InlineAttr;
6use rustc_data_structures::base_n::{BaseNString, CASE_INSENSITIVE, ToBaseN};
7use rustc_data_structures::fingerprint::Fingerprint;
8use rustc_data_structures::fx::FxIndexMap;
9use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher, ToStableHashKey};
10use rustc_data_structures::unord::UnordMap;
11use rustc_hir::ItemId;
12use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, LOCAL_CRATE};
13use rustc_index::Idx;
14use rustc_macros::{HashStable, TyDecodable, TyEncodable};
15use rustc_query_system::ich::StableHashingContext;
16use rustc_session::config::OptLevel;
17use rustc_span::{Span, Symbol};
18use rustc_target::spec::SymbolVisibility;
19use tracing::debug;
20
21use crate::dep_graph::{DepNode, WorkProduct, WorkProductId};
22use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
23use crate::ty::{GenericArgs, Instance, InstanceKind, SymbolName, TyCtxt};
24
25/// Describes how a monomorphization will be instantiated in object files.
26#[derive(PartialEq)]
27pub enum InstantiationMode {
28 /// There will be exactly one instance of the given MonoItem. It will have
29 /// external linkage so that it can be linked to from other codegen units.
30 GloballyShared {
31 /// In some compilation scenarios we may decide to take functions that
32 /// are typically `LocalCopy` and instead move them to `GloballyShared`
33 /// to avoid codegenning them a bunch of times. In this situation,
34 /// however, our local copy may conflict with other crates also
35 /// inlining the same function.
36 ///
37 /// This flag indicates that this situation is occurring, and informs
38 /// symbol name calculation that some extra mangling is needed to
39 /// avoid conflicts. Note that this may eventually go away entirely if
40 /// ThinLTO enables us to *always* have a globally shared instance of a
41 /// function within one crate's compilation.
42 may_conflict: bool,
43 },
44
45 /// Each codegen unit containing a reference to the given MonoItem will
46 /// have its own private copy of the function (with internal linkage).
47 LocalCopy,
48}
49
50#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, HashStable, TyEncodable, TyDecodable)]
51pub enum MonoItem<'tcx> {
52 Fn(Instance<'tcx>),
53 Static(DefId),
54 GlobalAsm(ItemId),
55}
56
57impl<'tcx> MonoItem<'tcx> {
58 /// Returns `true` if the mono item is user-defined (i.e. not compiler-generated, like shims).
59 pub fn is_user_defined(&self) -> bool {
60 match *self {
61 MonoItem::Fn(instance) => matches!(instance.def, InstanceKind::Item(..)),
62 MonoItem::Static(..) | MonoItem::GlobalAsm(..) => true,
63 }
64 }
65
66 // Note: if you change how item size estimates work, you might need to
67 // change NON_INCR_MIN_CGU_SIZE as well.
68 pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
69 match *self {
70 MonoItem::Fn(instance) => tcx.size_estimate(instance),
71 // Conservatively estimate the size of a static declaration or
72 // assembly item to be 1.
73 MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1,
74 }
75 }
76
77 pub fn is_generic_fn(&self) -> bool {
78 match self {
79 MonoItem::Fn(instance) => instance.args.non_erasable_generics().next().is_some(),
80 MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false,
81 }
82 }
83
84 pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName<'tcx> {
85 match *self {
86 MonoItem::Fn(instance) => tcx.symbol_name(instance),
87 MonoItem::Static(def_id) => tcx.symbol_name(Instance::mono(tcx, def_id)),
88 MonoItem::GlobalAsm(item_id) => {
89 SymbolName::new(tcx, &format!("global_asm_{:?}", item_id.owner_id))
90 }
91 }
92 }
93
94 pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
95 // The case handling here is written in the same style as cross_crate_inlinable, we first
96 // handle the cases where we must use a particular instantiation mode, then cascade down
97 // through a sequence of heuristics.
98
99 // The first thing we do is detect MonoItems which we must instantiate exactly once in the
100 // whole program.
101
102 // Statics and global_asm! must be instantiated exactly once.
103 let instance = match *self {
104 MonoItem::Fn(instance) => instance,
105 MonoItem::Static(..) | MonoItem::GlobalAsm(..) => {
106 return InstantiationMode::GloballyShared { may_conflict: false };
107 }
108 };
109
110 // Similarly, the executable entrypoint must be instantiated exactly once.
111 if let Some((entry_def_id, _)) = tcx.entry_fn(()) {
112 if instance.def_id() == entry_def_id {
113 return InstantiationMode::GloballyShared { may_conflict: false };
114 }
115 }
116
117 // If the function is #[naked] or contains any other attribute that requires exactly-once
118 // instantiation:
119 let codegen_fn_attrs = tcx.codegen_fn_attrs(instance.def_id());
120 if codegen_fn_attrs.contains_extern_indicator()
121 || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED)
122 {
123 return InstantiationMode::GloballyShared { may_conflict: false };
124 }
125
126 // FIXME: The logic for which functions are permitted to get LocalCopy is actually spread
127 // across 4 functions:
128 // * cross_crate_inlinable(def_id)
129 // * InstanceKind::requires_inline
130 // * InstanceKind::generate_cgu_internal_copy
131 // * MonoItem::instantiation_mode
132 // Since reachable_non_generics calls InstanceKind::generates_cgu_internal_copy to decide
133 // which symbols this crate exports, we are obligated to only generate LocalCopy when
134 // generates_cgu_internal_copy returns true.
135 if !instance.def.generates_cgu_internal_copy(tcx) {
136 return InstantiationMode::GloballyShared { may_conflict: false };
137 }
138
139 // Beginning of heuristics. The handling of link-dead-code and inline(always) are QoL only,
140 // the compiler should not crash and linkage should work, but codegen may be undesirable.
141
142 // -Clink-dead-code was given an unfortunate name; the point of the flag is to assist
143 // coverage tools which rely on having every function in the program appear in the
144 // generated code. If we select LocalCopy, functions which are not used because they are
145 // missing test coverage will disappear from such coverage reports, defeating the point.
146 // Note that -Cinstrument-coverage does not require such assistance from us, only coverage
147 // tools implemented without compiler support ironically require a special compiler flag.
148 if tcx.sess.link_dead_code() {
149 return InstantiationMode::GloballyShared { may_conflict: true };
150 }
151
152 // To ensure that #[inline(always)] can be inlined as much as possible, especially in unoptimized
153 // builds, we always select LocalCopy.
154 if codegen_fn_attrs.inline.always() {
155 return InstantiationMode::LocalCopy;
156 }
157
158 // #[inline(never)] functions in general are poor candidates for inlining and thus since
159 // LocalCopy generally increases code size for the benefit of optimizations from inlining,
160 // we want to give them GloballyShared codegen.
161 // The slight problem is that generic functions need to always support cross-crate
162 // compilation, so all previous stages of the compiler are obligated to treat generic
163 // functions the same as those that unconditionally get LocalCopy codegen. It's only when
164 // we get here that we can at least not codegen a #[inline(never)] generic function in all
165 // of our CGUs.
166 if let InlineAttr::Never = tcx.codegen_fn_attrs(instance.def_id()).inline
167 && self.is_generic_fn()
168 {
169 return InstantiationMode::GloballyShared { may_conflict: true };
170 }
171
172 // The fallthrough case is to generate LocalCopy for all optimized builds, and
173 // GloballyShared with conflict prevention when optimizations are disabled.
174 match tcx.sess.opts.optimize {
175 OptLevel::No => InstantiationMode::GloballyShared { may_conflict: true },
176 _ => InstantiationMode::LocalCopy,
177 }
178 }
179
180 pub fn explicit_linkage(&self, tcx: TyCtxt<'tcx>) -> Option<Linkage> {
181 let def_id = match *self {
182 MonoItem::Fn(ref instance) => instance.def_id(),
183 MonoItem::Static(def_id) => def_id,
184 MonoItem::GlobalAsm(..) => return None,
185 };
186
187 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
188 codegen_fn_attrs.linkage
189 }
190
191 /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
192 /// predicates.
193 ///
194 /// In order to codegen an item, all of its predicates must hold, because
195 /// otherwise the item does not make sense. Type-checking ensures that
196 /// the predicates of every item that is *used by* a valid item *do*
197 /// hold, so we can rely on that.
198 ///
199 /// However, we codegen collector roots (reachable items) and functions
200 /// in vtables when they are seen, even if they are not used, and so they
201 /// might not be instantiable. For example, a programmer can define this
202 /// public function:
203 ///
204 /// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
205 /// <&mut () as Clone>::clone(&s);
206 /// }
207 ///
208 /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
209 /// does not exist. Luckily for us, that function can't ever be used,
210 /// because that would require for `&'a mut (): Clone` to hold, so we
211 /// can just not emit any code, or even a linker reference for it.
212 ///
213 /// Similarly, if a vtable method has such a signature, and therefore can't
214 /// be used, we can just not emit it and have a placeholder (a null pointer,
215 /// which will never be accessed) in its place.
216 pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool {
217 debug!("is_instantiable({:?})", self);
218 let (def_id, args) = match *self {
219 MonoItem::Fn(ref instance) => (instance.def_id(), instance.args),
220 MonoItem::Static(def_id) => (def_id, GenericArgs::empty()),
221 // global asm never has predicates
222 MonoItem::GlobalAsm(..) => return true,
223 };
224
225 !tcx.instantiate_and_check_impossible_predicates((def_id, &args))
226 }
227
228 pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
229 match *self {
230 MonoItem::Fn(Instance { def, .. }) => def.def_id().as_local(),
231 MonoItem::Static(def_id) => def_id.as_local(),
232 MonoItem::GlobalAsm(item_id) => Some(item_id.owner_id.def_id),
233 }
234 .map(|def_id| tcx.def_span(def_id))
235 }
236
237 // Only used by rustc_codegen_cranelift
238 pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
239 crate::dep_graph::make_compile_mono_item(tcx, self)
240 }
241
242 /// Returns the item's `CrateNum`
243 pub fn krate(&self) -> CrateNum {
244 match self {
245 MonoItem::Fn(ref instance) => instance.def_id().krate,
246 MonoItem::Static(def_id) => def_id.krate,
247 MonoItem::GlobalAsm(..) => LOCAL_CRATE,
248 }
249 }
250
251 /// Returns the item's `DefId`
252 pub fn def_id(&self) -> DefId {
253 match *self {
254 MonoItem::Fn(Instance { def, .. }) => def.def_id(),
255 MonoItem::Static(def_id) => def_id,
256 MonoItem::GlobalAsm(item_id) => item_id.owner_id.to_def_id(),
257 }
258 }
259}
260
261impl<'tcx> fmt::Display for MonoItem<'tcx> {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 match *self {
264 MonoItem::Fn(instance) => write!(f, "fn {instance}"),
265 MonoItem::Static(def_id) => {
266 write!(f, "static {}", Instance::new(def_id, GenericArgs::empty()))
267 }
268 MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
269 }
270 }
271}
272
273impl ToStableHashKey<StableHashingContext<'_>> for MonoItem<'_> {
274 type KeyType = Fingerprint;
275
276 fn to_stable_hash_key(&self, hcx: &StableHashingContext<'_>) -> Self::KeyType {
277 let mut hasher = StableHasher::new();
278 self.hash_stable(&mut hcx.clone(), &mut hasher);
279 hasher.finish()
280 }
281}
282
283#[derive(Debug, HashStable, Copy, Clone)]
284pub struct MonoItemPartitions<'tcx> {
285 pub codegen_units: &'tcx [CodegenUnit<'tcx>],
286 pub all_mono_items: &'tcx DefIdSet,
287 pub autodiff_items: &'tcx [AutoDiffItem],
288}
289
290#[derive(Debug, HashStable)]
291pub struct CodegenUnit<'tcx> {
292 /// A name for this CGU. Incremental compilation requires that
293 /// name be unique amongst **all** crates. Therefore, it should
294 /// contain something unique to this crate (e.g., a module path)
295 /// as well as the crate name and disambiguator.
296 name: Symbol,
297 items: FxIndexMap<MonoItem<'tcx>, MonoItemData>,
298 size_estimate: usize,
299 primary: bool,
300 /// True if this is CGU is used to hold code coverage information for dead code,
301 /// false otherwise.
302 is_code_coverage_dead_code_cgu: bool,
303}
304
305/// Auxiliary info about a `MonoItem`.
306#[derive(Copy, Clone, PartialEq, Debug, HashStable)]
307pub struct MonoItemData {
308 /// A cached copy of the result of `MonoItem::instantiation_mode`, where
309 /// `GloballyShared` maps to `false` and `LocalCopy` maps to `true`.
310 pub inlined: bool,
311
312 pub linkage: Linkage,
313 pub visibility: Visibility,
314
315 /// A cached copy of the result of `MonoItem::size_estimate`.
316 pub size_estimate: usize,
317}
318
319/// Specifies the linkage type for a `MonoItem`.
320///
321/// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants.
322#[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
323pub enum Linkage {
324 External,
325 AvailableExternally,
326 LinkOnceAny,
327 LinkOnceODR,
328 WeakAny,
329 WeakODR,
330 Internal,
331 ExternalWeak,
332 Common,
333}
334
335/// Specifies the symbol visibility with regards to dynamic linking.
336///
337/// Visibility doesn't have any effect when linkage is internal.
338///
339/// DSO means dynamic shared object, that is a dynamically linked executable or dylib.
340#[derive(Copy, Clone, PartialEq, Debug, HashStable)]
341pub enum Visibility {
342 /// Export the symbol from the DSO and apply overrides of the symbol by outside DSOs to within
343 /// the DSO if the object file format supports this.
344 Default,
345 /// Hide the symbol outside of the defining DSO even when external linkage is used to export it
346 /// from the object file.
347 Hidden,
348 /// Export the symbol from the DSO, but don't apply overrides of the symbol by outside DSOs to
349 /// within the DSO. Equivalent to default visibility with object file formats that don't support
350 /// overriding exported symbols by another DSO.
351 Protected,
352}
353
354impl From<SymbolVisibility> for Visibility {
355 fn from(value: SymbolVisibility) -> Self {
356 match value {
357 SymbolVisibility::Hidden => Visibility::Hidden,
358 SymbolVisibility::Protected => Visibility::Protected,
359 SymbolVisibility::Interposable => Visibility::Default,
360 }
361 }
362}
363
364impl<'tcx> CodegenUnit<'tcx> {
365 #[inline]
366 pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
367 CodegenUnit {
368 name,
369 items: Default::default(),
370 size_estimate: 0,
371 primary: false,
372 is_code_coverage_dead_code_cgu: false,
373 }
374 }
375
376 pub fn name(&self) -> Symbol {
377 self.name
378 }
379
380 pub fn set_name(&mut self, name: Symbol) {
381 self.name = name;
382 }
383
384 pub fn is_primary(&self) -> bool {
385 self.primary
386 }
387
388 pub fn make_primary(&mut self) {
389 self.primary = true;
390 }
391
392 pub fn items(&self) -> &FxIndexMap<MonoItem<'tcx>, MonoItemData> {
393 &self.items
394 }
395
396 pub fn items_mut(&mut self) -> &mut FxIndexMap<MonoItem<'tcx>, MonoItemData> {
397 &mut self.items
398 }
399
400 pub fn is_code_coverage_dead_code_cgu(&self) -> bool {
401 self.is_code_coverage_dead_code_cgu
402 }
403
404 /// Marks this CGU as the one used to contain code coverage information for dead code.
405 pub fn make_code_coverage_dead_code_cgu(&mut self) {
406 self.is_code_coverage_dead_code_cgu = true;
407 }
408
409 pub fn mangle_name(human_readable_name: &str) -> BaseNString {
410 let mut hasher = StableHasher::new();
411 human_readable_name.hash(&mut hasher);
412 let hash: Hash128 = hasher.finish();
413 hash.as_u128().to_base_fixed_len(CASE_INSENSITIVE)
414 }
415
416 pub fn compute_size_estimate(&mut self) {
417 // The size of a codegen unit as the sum of the sizes of the items
418 // within it.
419 self.size_estimate = self.items.values().map(|data| data.size_estimate).sum();
420 }
421
422 /// Should only be called if [`compute_size_estimate`] has previously been called.
423 ///
424 /// [`compute_size_estimate`]: Self::compute_size_estimate
425 #[inline]
426 pub fn size_estimate(&self) -> usize {
427 // Items are never zero-sized, so if we have items the estimate must be
428 // non-zero, unless we forgot to call `compute_size_estimate` first.
429 assert!(self.items.is_empty() || self.size_estimate != 0);
430 self.size_estimate
431 }
432
433 pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
434 self.items().contains_key(item)
435 }
436
437 pub fn work_product_id(&self) -> WorkProductId {
438 WorkProductId::from_cgu_name(self.name().as_str())
439 }
440
441 pub fn previous_work_product(&self, tcx: TyCtxt<'_>) -> WorkProduct {
442 let work_product_id = self.work_product_id();
443 tcx.dep_graph
444 .previous_work_product(&work_product_id)
445 .unwrap_or_else(|| panic!("Could not find work-product for CGU `{}`", self.name()))
446 }
447
448 pub fn items_in_deterministic_order(
449 &self,
450 tcx: TyCtxt<'tcx>,
451 ) -> Vec<(MonoItem<'tcx>, MonoItemData)> {
452 // The codegen tests rely on items being process in the same order as
453 // they appear in the file, so for local items, we sort by node_id first
454 #[derive(PartialEq, Eq, PartialOrd, Ord)]
455 struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>);
456
457 fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> {
458 ItemSortKey(
459 match item {
460 MonoItem::Fn(ref instance) => {
461 match instance.def {
462 // We only want to take HirIds of user-defined
463 // instances into account. The others don't matter for
464 // the codegen tests and can even make item order
465 // unstable.
466 InstanceKind::Item(def) => def.as_local().map(Idx::index),
467 InstanceKind::VTableShim(..)
468 | InstanceKind::ReifyShim(..)
469 | InstanceKind::Intrinsic(..)
470 | InstanceKind::FnPtrShim(..)
471 | InstanceKind::Virtual(..)
472 | InstanceKind::ClosureOnceShim { .. }
473 | InstanceKind::ConstructCoroutineInClosureShim { .. }
474 | InstanceKind::DropGlue(..)
475 | InstanceKind::CloneShim(..)
476 | InstanceKind::ThreadLocalShim(..)
477 | InstanceKind::FnPtrAddrShim(..)
478 | InstanceKind::AsyncDropGlueCtorShim(..) => None,
479 }
480 }
481 MonoItem::Static(def_id) => def_id.as_local().map(Idx::index),
482 MonoItem::GlobalAsm(item_id) => Some(item_id.owner_id.def_id.index()),
483 },
484 item.symbol_name(tcx),
485 )
486 }
487
488 let mut items: Vec<_> = self.items().iter().map(|(&i, &data)| (i, data)).collect();
489 items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
490 items
491 }
492
493 pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
494 crate::dep_graph::make_compile_codegen_unit(tcx, self.name())
495 }
496}
497
498impl ToStableHashKey<StableHashingContext<'_>> for CodegenUnit<'_> {
499 type KeyType = String;
500
501 fn to_stable_hash_key(&self, _: &StableHashingContext<'_>) -> Self::KeyType {
502 // Codegen unit names are conceptually required to be stable across
503 // compilation session so that object file names match up.
504 self.name.to_string()
505 }
506}
507
508pub struct CodegenUnitNameBuilder<'tcx> {
509 tcx: TyCtxt<'tcx>,
510 cache: UnordMap<CrateNum, String>,
511}
512
513impl<'tcx> CodegenUnitNameBuilder<'tcx> {
514 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
515 CodegenUnitNameBuilder { tcx, cache: Default::default() }
516 }
517
518 /// CGU names should fulfill the following requirements:
519 /// - They should be able to act as a file name on any kind of file system
520 /// - They should not collide with other CGU names, even for different versions
521 /// of the same crate.
522 ///
523 /// Consequently, we don't use special characters except for '.' and '-' and we
524 /// prefix each name with the crate-name and crate-disambiguator.
525 ///
526 /// This function will build CGU names of the form:
527 ///
528 /// ```text
529 /// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
530 /// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
531 /// ```
532 ///
533 /// The '.' before `<special-suffix>` makes sure that names with a special
534 /// suffix can never collide with a name built out of regular Rust
535 /// identifiers (e.g., module paths).
536 pub fn build_cgu_name<I, C, S>(
537 &mut self,
538 cnum: CrateNum,
539 components: I,
540 special_suffix: Option<S>,
541 ) -> Symbol
542 where
543 I: IntoIterator<Item = C>,
544 C: fmt::Display,
545 S: fmt::Display,
546 {
547 let cgu_name = self.build_cgu_name_no_mangle(cnum, components, special_suffix);
548
549 if self.tcx.sess.opts.unstable_opts.human_readable_cgu_names {
550 cgu_name
551 } else {
552 Symbol::intern(&CodegenUnit::mangle_name(cgu_name.as_str()))
553 }
554 }
555
556 /// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
557 /// resulting name.
558 pub fn build_cgu_name_no_mangle<I, C, S>(
559 &mut self,
560 cnum: CrateNum,
561 components: I,
562 special_suffix: Option<S>,
563 ) -> Symbol
564 where
565 I: IntoIterator<Item = C>,
566 C: fmt::Display,
567 S: fmt::Display,
568 {
569 use std::fmt::Write;
570
571 let mut cgu_name = String::with_capacity(64);
572
573 // Start out with the crate name and disambiguator
574 let tcx = self.tcx;
575 let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
576 // Whenever the cnum is not LOCAL_CRATE we also mix in the
577 // local crate's ID. Otherwise there can be collisions between CGUs
578 // instantiating stuff for upstream crates.
579 let local_crate_id = if cnum != LOCAL_CRATE {
580 let local_stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
581 format!("-in-{}.{:08x}", tcx.crate_name(LOCAL_CRATE), local_stable_crate_id)
582 } else {
583 String::new()
584 };
585
586 let stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
587 format!("{}.{:08x}{}", tcx.crate_name(cnum), stable_crate_id, local_crate_id)
588 });
589
590 write!(cgu_name, "{crate_prefix}").unwrap();
591
592 // Add the components
593 for component in components {
594 write!(cgu_name, "-{component}").unwrap();
595 }
596
597 if let Some(special_suffix) = special_suffix {
598 // We add a dot in here so it cannot clash with anything in a regular
599 // Rust identifier
600 write!(cgu_name, ".{special_suffix}").unwrap();
601 }
602
603 Symbol::intern(&cgu_name)
604 }
605}
606
607/// See module-level docs of `rustc_monomorphize::collector` on some context for "mentioned" items.
608#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
609pub enum CollectionMode {
610 /// Collect items that are used, i.e., actually needed for codegen.
611 ///
612 /// Which items are used can depend on optimization levels, as MIR optimizations can remove
613 /// uses.
614 UsedItems,
615 /// Collect items that are mentioned. The goal of this mode is that it is independent of
616 /// optimizations: the set of "mentioned" items is computed before optimizations are run.
617 ///
618 /// The exact contents of this set are *not* a stable guarantee. (For instance, it is currently
619 /// computed after drop-elaboration. If we ever do some optimizations even in debug builds, we
620 /// might decide to run them before computing mentioned items.) The key property of this set is
621 /// that it is optimization-independent.
622 MentionedItems,
623}