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