1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Walks the crate looking for items/impl-items/trait-items that have
12 //! either a `rustc_symbol_name` or `rustc_item_path` attribute and
13 //! generates an error giving, respectively, the symbol name or
14 //! item-path. This is used for unit testing the code that generates
15 //! paths etc in all kinds of annoying scenarios.
17 use monomorphize::Instance;
19 use rustc::hir::def_id::DefId;
20 use rustc::session::config::OptLevel;
21 use rustc::ty::{self, Ty, TyCtxt, ClosureSubsts, GeneratorSubsts};
22 use rustc::ty::subst::Substs;
24 use syntax::attr::InlineAttr;
25 use std::fmt::{self, Write};
27 use rustc::mir::mono::Linkage;
28 use syntax_pos::symbol::Symbol;
29 use syntax::codemap::Span;
30 pub use rustc::mir::mono::MonoItem;
32 /// Describes how a monomorphization will be instantiated in object files.
33 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
34 pub enum InstantiationMode {
35 /// There will be exactly one instance of the given MonoItem. It will have
36 /// external linkage so that it can be linked to from other codegen units.
38 /// In some compilation scenarios we may decide to take functions that
39 /// are typically `LocalCopy` and instead move them to `GloballyShared`
40 /// to avoid codegenning them a bunch of times. In this situation,
41 /// however, our local copy may conflict with other crates also
42 /// inlining the same function.
44 /// This flag indicates that this situation is occurring, and informs
45 /// symbol name calculation that some extra mangling is needed to
46 /// avoid conflicts. Note that this may eventually go away entirely if
47 /// ThinLTO enables us to *always* have a globally shared instance of a
48 /// function within one crate's compilation.
52 /// Each codegen unit containing a reference to the given MonoItem will
53 /// have its own private copy of the function (with internal linkage).
57 pub trait MonoItemExt<'a, 'tcx>: fmt::Debug {
58 fn as_mono_item(&self) -> &MonoItem<'tcx>;
60 fn is_generic_fn(&self) -> bool {
61 match *self.as_mono_item() {
62 MonoItem::Fn(ref instance) => {
63 instance.substs.types().next().is_some()
65 MonoItem::Static(..) |
66 MonoItem::CustomSection(..) |
67 MonoItem::GlobalAsm(..) => false,
71 fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
72 match *self.as_mono_item() {
73 MonoItem::Fn(instance) => tcx.symbol_name(instance),
74 MonoItem::Static(def_id) => {
75 tcx.symbol_name(Instance::mono(tcx, def_id))
77 MonoItem::CustomSection(def_id) => {
78 tcx.symbol_name(Instance::mono(tcx, def_id))
80 MonoItem::GlobalAsm(node_id) => {
81 let def_id = tcx.hir.local_def_id(node_id);
83 name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_interned_str()
88 fn instantiation_mode(&self,
89 tcx: TyCtxt<'a, 'tcx, 'tcx>)
90 -> InstantiationMode {
91 let inline_in_all_cgus =
92 tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
93 tcx.sess.opts.optimize != OptLevel::No
94 }) && !tcx.sess.opts.cg.link_dead_code;
96 match *self.as_mono_item() {
97 MonoItem::Fn(ref instance) => {
99 tcx.sess.entry_fn.borrow().map(|(id, _, _)| tcx.hir.local_def_id(id));
100 // If this function isn't inlined or otherwise has explicit
101 // linkage, then we'll be creating a globally shared version.
102 if self.explicit_linkage(tcx).is_some() ||
103 !instance.def.requires_local(tcx) ||
104 Some(instance.def_id()) == entry_def_id
106 return InstantiationMode::GloballyShared { may_conflict: false }
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 inline_in_all_cgus {
113 return InstantiationMode::LocalCopy
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
121 match tcx.codegen_fn_attrs(instance.def_id()).inline {
122 InlineAttr::Always => InstantiationMode::LocalCopy,
124 InstantiationMode::GloballyShared { may_conflict: true }
128 MonoItem::Static(..) |
129 MonoItem::CustomSection(..) |
130 MonoItem::GlobalAsm(..) => {
131 InstantiationMode::GloballyShared { may_conflict: false }
136 fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Linkage> {
137 let def_id = match *self.as_mono_item() {
138 MonoItem::Fn(ref instance) => instance.def_id(),
139 MonoItem::Static(def_id) => def_id,
140 MonoItem::CustomSection(..) => return None,
141 MonoItem::GlobalAsm(..) => return None,
144 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
145 codegen_fn_attrs.linkage
148 /// Returns whether this instance is instantiable - whether it has no unsatisfied
151 /// In order to codegen an item, all of its predicates must hold, because
152 /// otherwise the item does not make sense. Type-checking ensures that
153 /// the predicates of every item that is *used by* a valid item *do*
154 /// hold, so we can rely on that.
156 /// However, we codegen collector roots (reachable items) and functions
157 /// in vtables when they are seen, even if they are not used, and so they
158 /// might not be instantiable. For example, a programmer can define this
161 /// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
162 /// <&mut () as Clone>::clone(&s);
165 /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
166 /// does not exist. Luckily for us, that function can't ever be used,
167 /// because that would require for `&'a mut (): Clone` to hold, so we
168 /// can just not emit any code, or even a linker reference for it.
170 /// Similarly, if a vtable method has such a signature, and therefore can't
171 /// be used, we can just not emit it and have a placeholder (a null pointer,
172 /// which will never be accessed) in its place.
173 fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
174 debug!("is_instantiable({:?})", self);
175 let (def_id, substs) = match *self.as_mono_item() {
176 MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
177 MonoItem::Static(def_id) => (def_id, Substs::empty()),
178 MonoItem::CustomSection(..) => return true,
179 // global asm never has predicates
180 MonoItem::GlobalAsm(..) => return true
183 tcx.substitute_normalize_and_test_predicates((def_id, &substs))
186 fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
187 return match *self.as_mono_item() {
188 MonoItem::Fn(instance) => {
189 to_string_internal(tcx, "fn ", instance)
191 MonoItem::Static(def_id) => {
192 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
193 to_string_internal(tcx, "static ", instance)
195 MonoItem::CustomSection(def_id) => {
196 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
197 to_string_internal(tcx, "custom-section ", instance)
199 MonoItem::GlobalAsm(..) => {
200 "global_asm".to_string()
204 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
206 instance: Instance<'tcx>)
208 let mut result = String::with_capacity(32);
209 result.push_str(prefix);
210 let printer = DefPathBasedNames::new(tcx, false, false);
211 printer.push_instance_as_string(instance, &mut result);
216 fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
217 match *self.as_mono_item() {
218 MonoItem::Fn(Instance { def, .. }) => {
219 tcx.hir.as_local_node_id(def.def_id())
221 MonoItem::Static(def_id) => {
222 tcx.hir.as_local_node_id(def_id)
224 MonoItem::CustomSection(def_id) => {
225 tcx.hir.as_local_node_id(def_id)
227 MonoItem::GlobalAsm(node_id) => {
230 }.map(|node_id| tcx.hir.span(node_id))
234 impl<'a, 'tcx> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
235 fn as_mono_item(&self) -> &MonoItem<'tcx> {
240 //=-----------------------------------------------------------------------------
241 // MonoItem String Keys
242 //=-----------------------------------------------------------------------------
244 // The code below allows for producing a unique string key for a mono item.
245 // These keys are used by the handwritten auto-tests, so they need to be
246 // predictable and human-readable.
248 // Note: A lot of this could looks very similar to what's already in the
249 // ppaux module. It would be good to refactor things so we only have one
250 // parameterizable implementation for printing types.
252 /// Same as `unique_type_name()` but with the result pushed onto the given
253 /// `output` parameter.
254 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
255 tcx: TyCtxt<'a, 'tcx, 'tcx>,
256 omit_disambiguators: bool,
257 omit_local_crate_name: bool,
260 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
261 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
262 omit_disambiguators: bool,
263 omit_local_crate_name: bool)
268 omit_local_crate_name,
272 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
274 ty::TyBool => output.push_str("bool"),
275 ty::TyChar => output.push_str("char"),
276 ty::TyStr => output.push_str("str"),
277 ty::TyNever => output.push_str("!"),
278 ty::TyInt(ast::IntTy::Isize) => output.push_str("isize"),
279 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
280 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
281 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
282 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
283 ty::TyInt(ast::IntTy::I128) => output.push_str("i128"),
284 ty::TyUint(ast::UintTy::Usize) => output.push_str("usize"),
285 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
286 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
287 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
288 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
289 ty::TyUint(ast::UintTy::U128) => output.push_str("u128"),
290 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
291 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
292 ty::TyAdt(adt_def, substs) => {
293 self.push_def_path(adt_def.did, output);
294 self.push_type_params(substs, iter::empty(), output);
296 ty::TyTuple(component_types) => {
298 for &component_type in component_types {
299 self.push_type_name(component_type, output);
300 output.push_str(", ");
302 if !component_types.is_empty() {
308 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
311 hir::MutImmutable => output.push_str("const "),
312 hir::MutMutable => output.push_str("mut "),
315 self.push_type_name(inner_type, output);
317 ty::TyRef(_, inner_type, mutbl) => {
319 if mutbl == hir::MutMutable {
320 output.push_str("mut ");
323 self.push_type_name(inner_type, output);
325 ty::TyArray(inner_type, len) => {
327 self.push_type_name(inner_type, output);
328 write!(output, "; {}", len.unwrap_usize(self.tcx)).unwrap();
331 ty::TySlice(inner_type) => {
333 self.push_type_name(inner_type, output);
336 ty::TyDynamic(ref trait_data, ..) => {
337 if let Some(principal) = trait_data.principal() {
338 self.push_def_path(principal.def_id(), output);
339 self.push_type_params(principal.skip_binder().substs,
340 trait_data.projection_bounds(),
344 ty::TyForeign(did) => self.push_def_path(did, output),
347 let sig = t.fn_sig(self.tcx);
348 if sig.unsafety() == hir::Unsafety::Unsafe {
349 output.push_str("unsafe ");
353 if abi != ::rustc_target::spec::abi::Abi::Rust {
354 output.push_str("extern \"");
355 output.push_str(abi.name());
356 output.push_str("\" ");
359 output.push_str("fn(");
361 let sig = self.tcx.normalize_erasing_late_bound_regions(
362 ty::ParamEnv::reveal_all(),
366 if !sig.inputs().is_empty() {
367 for ¶meter_type in sig.inputs() {
368 self.push_type_name(parameter_type, output);
369 output.push_str(", ");
376 if !sig.inputs().is_empty() {
377 output.push_str(", ...");
379 output.push_str("...");
385 if !sig.output().is_nil() {
386 output.push_str(" -> ");
387 self.push_type_name(sig.output(), output);
390 ty::TyGenerator(def_id, GeneratorSubsts { ref substs }, _) |
391 ty::TyClosure(def_id, ClosureSubsts { ref substs }) => {
392 self.push_def_path(def_id, output);
393 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
394 let substs = substs.truncate_to(self.tcx, generics);
395 self.push_type_params(substs, iter::empty(), output);
399 ty::TyProjection(..) |
401 ty::TyGeneratorWitness(_) |
403 bug!("DefPathBasedNames: Trying to create type name for \
404 unexpected type: {:?}", t);
409 pub fn push_def_path(&self,
411 output: &mut String) {
412 let def_path = self.tcx.def_path(def_id);
415 if !(self.omit_local_crate_name && def_id.is_local()) {
416 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
417 output.push_str("::");
420 // foo::bar::ItemName::
421 for part in self.tcx.def_path(def_id).data {
422 if self.omit_disambiguators {
423 write!(output, "{}::", part.data.as_interned_str()).unwrap();
425 write!(output, "{}[{}]::",
426 part.data.as_interned_str(),
427 part.disambiguator).unwrap();
436 fn push_type_params<I>(&self,
437 substs: &Substs<'tcx>,
440 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
442 let mut projections = projections.peekable();
443 if substs.types().next().is_none() && projections.peek().is_none() {
449 for type_parameter in substs.types() {
450 self.push_type_name(type_parameter, output);
451 output.push_str(", ");
454 for projection in projections {
455 let projection = projection.skip_binder();
456 let name = &self.tcx.associated_item(projection.item_def_id).ident.as_str();
457 output.push_str(name);
458 output.push_str("=");
459 self.push_type_name(projection.ty, output);
460 output.push_str(", ");
469 pub fn push_instance_as_string(&self,
470 instance: Instance<'tcx>,
471 output: &mut String) {
472 self.push_def_path(instance.def_id(), output);
473 self.push_type_params(instance.substs, iter::empty(), output);