]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mono.rs
Rollup merge of #92399 - Veeupup:fix_vec_typo, r=Dylan-DPC
[rust.git] / compiler / rustc_middle / src / mir / mono.rs
1 use crate::dep_graph::{DepNode, WorkProduct, WorkProductId};
2 use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt};
3 use rustc_attr::InlineAttr;
4 use rustc_data_structures::base_n;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
9 use rustc_hir::ItemId;
10 use rustc_query_system::ich::{NodeIdHashingMode, StableHashingContext};
11 use rustc_session::config::OptLevel;
12 use rustc_span::source_map::Span;
13 use rustc_span::symbol::Symbol;
14 use std::fmt;
15 use std::hash::Hash;
16
17 /// Describes how a monomorphization will be instantiated in object files.
18 #[derive(PartialEq)]
19 pub enum InstantiationMode {
20     /// There will be exactly one instance of the given MonoItem. It will have
21     /// external linkage so that it can be linked to from other codegen units.
22     GloballyShared {
23         /// In some compilation scenarios we may decide to take functions that
24         /// are typically `LocalCopy` and instead move them to `GloballyShared`
25         /// to avoid codegenning them a bunch of times. In this situation,
26         /// however, our local copy may conflict with other crates also
27         /// inlining the same function.
28         ///
29         /// This flag indicates that this situation is occurring, and informs
30         /// symbol name calculation that some extra mangling is needed to
31         /// avoid conflicts. Note that this may eventually go away entirely if
32         /// ThinLTO enables us to *always* have a globally shared instance of a
33         /// function within one crate's compilation.
34         may_conflict: bool,
35     },
36
37     /// Each codegen unit containing a reference to the given MonoItem will
38     /// have its own private copy of the function (with internal linkage).
39     LocalCopy,
40 }
41
42 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
43 pub enum MonoItem<'tcx> {
44     Fn(Instance<'tcx>),
45     Static(DefId),
46     GlobalAsm(ItemId),
47 }
48
49 impl<'tcx> MonoItem<'tcx> {
50     /// Returns `true` if the mono item is user-defined (i.e. not compiler-generated, like shims).
51     pub fn is_user_defined(&self) -> bool {
52         match *self {
53             MonoItem::Fn(instance) => matches!(instance.def, InstanceDef::Item(..)),
54             MonoItem::Static(..) | MonoItem::GlobalAsm(..) => true,
55         }
56     }
57
58     pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
59         match *self {
60             MonoItem::Fn(instance) => {
61                 // Estimate the size of a function based on how many statements
62                 // it contains.
63                 tcx.instance_def_size_estimate(instance.def)
64             }
65             // Conservatively estimate the size of a static declaration
66             // or assembly to be 1.
67             MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1,
68         }
69     }
70
71     pub fn is_generic_fn(&self) -> bool {
72         match *self {
73             MonoItem::Fn(ref instance) => instance.substs.non_erasable_generics().next().is_some(),
74             MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false,
75         }
76     }
77
78     pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName<'tcx> {
79         match *self {
80             MonoItem::Fn(instance) => tcx.symbol_name(instance),
81             MonoItem::Static(def_id) => tcx.symbol_name(Instance::mono(tcx, def_id)),
82             MonoItem::GlobalAsm(item_id) => {
83                 SymbolName::new(tcx, &format!("global_asm_{:?}", item_id.def_id))
84             }
85         }
86     }
87
88     pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
89         let generate_cgu_internal_copies = tcx
90             .sess
91             .opts
92             .debugging_opts
93             .inline_in_all_cgus
94             .unwrap_or_else(|| tcx.sess.opts.optimize != OptLevel::No)
95             && !tcx.sess.link_dead_code();
96
97         match *self {
98             MonoItem::Fn(ref instance) => {
99                 let entry_def_id = tcx.entry_fn(()).map(|(id, _)| id);
100                 // If this function isn't inlined or otherwise has an extern
101                 // indicator, then we'll be creating a globally shared version.
102                 if tcx.codegen_fn_attrs(instance.def_id()).contains_extern_indicator()
103                     || !instance.def.generates_cgu_internal_copy(tcx)
104                     || Some(instance.def_id()) == entry_def_id
105                 {
106                     return InstantiationMode::GloballyShared { may_conflict: false };
107                 }
108
109                 // At this point we don't have explicit linkage and we're an
110                 // inlined function. If we're inlining into all CGUs then we'll
111                 // be creating a local copy per CGU.
112                 if generate_cgu_internal_copies {
113                     return InstantiationMode::LocalCopy;
114                 }
115
116                 // Finally, if this is `#[inline(always)]` we're sure to respect
117                 // that with an inline copy per CGU, but otherwise we'll be
118                 // creating one copy of this `#[inline]` function which may
119                 // conflict with upstream crates as it could be an exported
120                 // symbol.
121                 match tcx.codegen_fn_attrs(instance.def_id()).inline {
122                     InlineAttr::Always => InstantiationMode::LocalCopy,
123                     _ => InstantiationMode::GloballyShared { may_conflict: true },
124                 }
125             }
126             MonoItem::Static(..) | MonoItem::GlobalAsm(..) => {
127                 InstantiationMode::GloballyShared { may_conflict: false }
128             }
129         }
130     }
131
132     pub fn explicit_linkage(&self, tcx: TyCtxt<'tcx>) -> Option<Linkage> {
133         let def_id = match *self {
134             MonoItem::Fn(ref instance) => instance.def_id(),
135             MonoItem::Static(def_id) => def_id,
136             MonoItem::GlobalAsm(..) => return None,
137         };
138
139         let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
140         codegen_fn_attrs.linkage
141     }
142
143     /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
144     /// predicates.
145     ///
146     /// In order to codegen an item, all of its predicates must hold, because
147     /// otherwise the item does not make sense. Type-checking ensures that
148     /// the predicates of every item that is *used by* a valid item *do*
149     /// hold, so we can rely on that.
150     ///
151     /// However, we codegen collector roots (reachable items) and functions
152     /// in vtables when they are seen, even if they are not used, and so they
153     /// might not be instantiable. For example, a programmer can define this
154     /// public function:
155     ///
156     ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
157     ///         <&mut () as Clone>::clone(&s);
158     ///     }
159     ///
160     /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
161     /// does not exist. Luckily for us, that function can't ever be used,
162     /// because that would require for `&'a mut (): Clone` to hold, so we
163     /// can just not emit any code, or even a linker reference for it.
164     ///
165     /// Similarly, if a vtable method has such a signature, and therefore can't
166     /// be used, we can just not emit it and have a placeholder (a null pointer,
167     /// which will never be accessed) in its place.
168     pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool {
169         debug!("is_instantiable({:?})", self);
170         let (def_id, substs) = match *self {
171             MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
172             MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
173             // global asm never has predicates
174             MonoItem::GlobalAsm(..) => return true,
175         };
176
177         !tcx.subst_and_check_impossible_predicates((def_id, &substs))
178     }
179
180     pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
181         match *self {
182             MonoItem::Fn(Instance { def, .. }) => def.def_id().as_local(),
183             MonoItem::Static(def_id) => def_id.as_local(),
184             MonoItem::GlobalAsm(item_id) => Some(item_id.def_id),
185         }
186         .map(|def_id| tcx.def_span(def_id))
187     }
188
189     // Only used by rustc_codegen_cranelift
190     pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
191         crate::dep_graph::make_compile_mono_item(tcx, self)
192     }
193
194     /// Returns the item's `CrateNum`
195     pub fn krate(&self) -> CrateNum {
196         match self {
197             MonoItem::Fn(ref instance) => instance.def_id().krate,
198             MonoItem::Static(def_id) => def_id.krate,
199             MonoItem::GlobalAsm(..) => LOCAL_CRATE,
200         }
201     }
202 }
203
204 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {
205     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
206         ::std::mem::discriminant(self).hash_stable(hcx, hasher);
207
208         match *self {
209             MonoItem::Fn(ref instance) => {
210                 instance.hash_stable(hcx, hasher);
211             }
212             MonoItem::Static(def_id) => {
213                 def_id.hash_stable(hcx, hasher);
214             }
215             MonoItem::GlobalAsm(item_id) => {
216                 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
217                     item_id.hash_stable(hcx, hasher);
218                 })
219             }
220         }
221     }
222 }
223
224 impl<'tcx> fmt::Display for MonoItem<'tcx> {
225     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226         match *self {
227             MonoItem::Fn(instance) => write!(f, "fn {}", instance),
228             MonoItem::Static(def_id) => {
229                 write!(f, "static {}", Instance::new(def_id, InternalSubsts::empty()))
230             }
231             MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
232         }
233     }
234 }
235
236 #[derive(Debug)]
237 pub struct CodegenUnit<'tcx> {
238     /// A name for this CGU. Incremental compilation requires that
239     /// name be unique amongst **all** crates. Therefore, it should
240     /// contain something unique to this crate (e.g., a module path)
241     /// as well as the crate name and disambiguator.
242     name: Symbol,
243     items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>,
244     size_estimate: Option<usize>,
245     primary: bool,
246     /// True if this is CGU is used to hold code coverage information for dead code,
247     /// false otherwise.
248     is_code_coverage_dead_code_cgu: bool,
249 }
250
251 /// Specifies the linkage type for a `MonoItem`.
252 ///
253 /// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants.
254 #[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
255 pub enum Linkage {
256     External,
257     AvailableExternally,
258     LinkOnceAny,
259     LinkOnceODR,
260     WeakAny,
261     WeakODR,
262     Appending,
263     Internal,
264     Private,
265     ExternalWeak,
266     Common,
267 }
268
269 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
270 pub enum Visibility {
271     Default,
272     Hidden,
273     Protected,
274 }
275
276 impl<'tcx> CodegenUnit<'tcx> {
277     #[inline]
278     pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
279         CodegenUnit {
280             name,
281             items: Default::default(),
282             size_estimate: None,
283             primary: false,
284             is_code_coverage_dead_code_cgu: false,
285         }
286     }
287
288     pub fn name(&self) -> Symbol {
289         self.name
290     }
291
292     pub fn set_name(&mut self, name: Symbol) {
293         self.name = name;
294     }
295
296     pub fn is_primary(&self) -> bool {
297         self.primary
298     }
299
300     pub fn make_primary(&mut self) {
301         self.primary = true;
302     }
303
304     pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
305         &self.items
306     }
307
308     pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
309         &mut self.items
310     }
311
312     pub fn is_code_coverage_dead_code_cgu(&self) -> bool {
313         self.is_code_coverage_dead_code_cgu
314     }
315
316     /// Marks this CGU as the one used to contain code coverage information for dead code.
317     pub fn make_code_coverage_dead_code_cgu(&mut self) {
318         self.is_code_coverage_dead_code_cgu = true;
319     }
320
321     pub fn mangle_name(human_readable_name: &str) -> String {
322         // We generate a 80 bit hash from the name. This should be enough to
323         // avoid collisions and is still reasonably short for filenames.
324         let mut hasher = StableHasher::new();
325         human_readable_name.hash(&mut hasher);
326         let hash: u128 = hasher.finish();
327         let hash = hash & ((1u128 << 80) - 1);
328         base_n::encode(hash, base_n::CASE_INSENSITIVE)
329     }
330
331     pub fn estimate_size(&mut self, tcx: TyCtxt<'tcx>) {
332         // Estimate the size of a codegen unit as (approximately) the number of MIR
333         // statements it corresponds to.
334         self.size_estimate = Some(self.items.keys().map(|mi| mi.size_estimate(tcx)).sum());
335     }
336
337     #[inline]
338     pub fn size_estimate(&self) -> usize {
339         // Should only be called if `estimate_size` has previously been called.
340         self.size_estimate.expect("estimate_size must be called before getting a size_estimate")
341     }
342
343     pub fn modify_size_estimate(&mut self, delta: usize) {
344         assert!(self.size_estimate.is_some());
345         if let Some(size_estimate) = self.size_estimate {
346             self.size_estimate = Some(size_estimate + delta);
347         }
348     }
349
350     pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
351         self.items().contains_key(item)
352     }
353
354     pub fn work_product_id(&self) -> WorkProductId {
355         WorkProductId::from_cgu_name(self.name().as_str())
356     }
357
358     pub fn work_product(&self, tcx: TyCtxt<'_>) -> WorkProduct {
359         let work_product_id = self.work_product_id();
360         tcx.dep_graph
361             .previous_work_product(&work_product_id)
362             .unwrap_or_else(|| panic!("Could not find work-product for CGU `{}`", self.name()))
363     }
364
365     pub fn items_in_deterministic_order(
366         &self,
367         tcx: TyCtxt<'tcx>,
368     ) -> Vec<(MonoItem<'tcx>, (Linkage, Visibility))> {
369         // The codegen tests rely on items being process in the same order as
370         // they appear in the file, so for local items, we sort by node_id first
371         #[derive(PartialEq, Eq, PartialOrd, Ord)]
372         pub struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>);
373
374         fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> {
375             ItemSortKey(
376                 match item {
377                     MonoItem::Fn(ref instance) => {
378                         match instance.def {
379                             // We only want to take HirIds of user-defined
380                             // instances into account. The others don't matter for
381                             // the codegen tests and can even make item order
382                             // unstable.
383                             InstanceDef::Item(def) => Some(def.did.index.as_usize()),
384                             InstanceDef::VtableShim(..)
385                             | InstanceDef::ReifyShim(..)
386                             | InstanceDef::Intrinsic(..)
387                             | InstanceDef::FnPtrShim(..)
388                             | InstanceDef::Virtual(..)
389                             | InstanceDef::ClosureOnceShim { .. }
390                             | InstanceDef::DropGlue(..)
391                             | InstanceDef::CloneShim(..) => None,
392                         }
393                     }
394                     MonoItem::Static(def_id) => Some(def_id.index.as_usize()),
395                     MonoItem::GlobalAsm(item_id) => {
396                         Some(item_id.def_id.to_def_id().index.as_usize())
397                     }
398                 },
399                 item.symbol_name(tcx),
400             )
401         }
402
403         let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
404         items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
405         items
406     }
407
408     pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
409         crate::dep_graph::make_compile_codegen_unit(tcx, self.name())
410     }
411 }
412
413 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for CodegenUnit<'tcx> {
414     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
415         let CodegenUnit {
416             ref items,
417             name,
418             // The size estimate is not relevant to the hash
419             size_estimate: _,
420             primary: _,
421             is_code_coverage_dead_code_cgu,
422         } = *self;
423
424         name.hash_stable(hcx, hasher);
425         is_code_coverage_dead_code_cgu.hash_stable(hcx, hasher);
426
427         let mut items: Vec<(Fingerprint, _)> = items
428             .iter()
429             .map(|(mono_item, &attrs)| {
430                 let mut hasher = StableHasher::new();
431                 mono_item.hash_stable(hcx, &mut hasher);
432                 let mono_item_fingerprint = hasher.finish();
433                 (mono_item_fingerprint, attrs)
434             })
435             .collect();
436
437         items.sort_unstable_by_key(|i| i.0);
438         items.hash_stable(hcx, hasher);
439     }
440 }
441
442 pub struct CodegenUnitNameBuilder<'tcx> {
443     tcx: TyCtxt<'tcx>,
444     cache: FxHashMap<CrateNum, String>,
445 }
446
447 impl<'tcx> CodegenUnitNameBuilder<'tcx> {
448     pub fn new(tcx: TyCtxt<'tcx>) -> Self {
449         CodegenUnitNameBuilder { tcx, cache: Default::default() }
450     }
451
452     /// CGU names should fulfill the following requirements:
453     /// - They should be able to act as a file name on any kind of file system
454     /// - They should not collide with other CGU names, even for different versions
455     ///   of the same crate.
456     ///
457     /// Consequently, we don't use special characters except for '.' and '-' and we
458     /// prefix each name with the crate-name and crate-disambiguator.
459     ///
460     /// This function will build CGU names of the form:
461     ///
462     /// ```
463     /// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
464     /// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
465     /// ```
466     ///
467     /// The '.' before `<special-suffix>` makes sure that names with a special
468     /// suffix can never collide with a name built out of regular Rust
469     /// identifiers (e.g., module paths).
470     pub fn build_cgu_name<I, C, S>(
471         &mut self,
472         cnum: CrateNum,
473         components: I,
474         special_suffix: Option<S>,
475     ) -> Symbol
476     where
477         I: IntoIterator<Item = C>,
478         C: fmt::Display,
479         S: fmt::Display,
480     {
481         let cgu_name = self.build_cgu_name_no_mangle(cnum, components, special_suffix);
482
483         if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
484             cgu_name
485         } else {
486             Symbol::intern(&CodegenUnit::mangle_name(cgu_name.as_str()))
487         }
488     }
489
490     /// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
491     /// resulting name.
492     pub fn build_cgu_name_no_mangle<I, C, S>(
493         &mut self,
494         cnum: CrateNum,
495         components: I,
496         special_suffix: Option<S>,
497     ) -> Symbol
498     where
499         I: IntoIterator<Item = C>,
500         C: fmt::Display,
501         S: fmt::Display,
502     {
503         use std::fmt::Write;
504
505         let mut cgu_name = String::with_capacity(64);
506
507         // Start out with the crate name and disambiguator
508         let tcx = self.tcx;
509         let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
510             // Whenever the cnum is not LOCAL_CRATE we also mix in the
511             // local crate's ID. Otherwise there can be collisions between CGUs
512             // instantiating stuff for upstream crates.
513             let local_crate_id = if cnum != LOCAL_CRATE {
514                 let local_stable_crate_id = tcx.sess.local_stable_crate_id();
515                 format!(
516                     "-in-{}.{:08x}",
517                     tcx.crate_name(LOCAL_CRATE),
518                     local_stable_crate_id.to_u64() as u32,
519                 )
520             } else {
521                 String::new()
522             };
523
524             let stable_crate_id = tcx.sess.local_stable_crate_id();
525             format!(
526                 "{}.{:08x}{}",
527                 tcx.crate_name(cnum),
528                 stable_crate_id.to_u64() as u32,
529                 local_crate_id,
530             )
531         });
532
533         write!(cgu_name, "{}", crate_prefix).unwrap();
534
535         // Add the components
536         for component in components {
537             write!(cgu_name, "-{}", component).unwrap();
538         }
539
540         if let Some(special_suffix) = special_suffix {
541             // We add a dot in here so it cannot clash with anything in a regular
542             // Rust identifier
543             write!(cgu_name, ".{}", special_suffix).unwrap();
544         }
545
546         Symbol::intern(&cgu_name)
547     }
548 }