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.
21 use context::CrateContext;
25 use monomorphize::Instance;
27 use rustc::hir::def_id::DefId;
28 use rustc::middle::trans::{Linkage, Visibility};
29 use rustc::session::config::OptLevel;
31 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
32 use rustc::ty::subst::{Subst, Substs};
36 use syntax_pos::symbol::Symbol;
38 use std::fmt::{self, Write};
41 pub use rustc::middle::trans::TransItem;
43 /// Describes how a translation item will be instantiated in object files.
44 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
45 pub enum InstantiationMode {
46 /// There will be exactly one instance of the given TransItem. It will have
47 /// external linkage so that it can be linked to from other codegen units.
49 /// In some compilation scenarios we may decide to take functions that
50 /// are typically `LocalCopy` and instead move them to `GloballyShared`
51 /// to avoid translating them a bunch of times. In this situation,
52 /// however, our local copy may conflict with other crates also
53 /// inlining the same function.
55 /// This flag indicates that this situation is occuring, and informs
56 /// symbol name calculation that some extra mangling is needed to
57 /// avoid conflicts. Note that this may eventually go away entirely if
58 /// ThinLTO enables us to *always* have a globally shared instance of a
59 /// function within one crate's compilation.
63 /// Each codegen unit containing a reference to the given TransItem will
64 /// have its own private copy of the function (with internal linkage).
68 pub trait TransItemExt<'a, 'tcx>: fmt::Debug {
69 fn as_trans_item(&self) -> &TransItem<'tcx>;
71 fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
72 debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
73 self.to_string(ccx.tcx()),
75 ccx.codegen_unit().name());
77 match *self.as_trans_item() {
78 TransItem::Static(node_id) => {
80 let item = tcx.hir.expect_item(node_id);
81 if let hir::ItemStatic(_, m, _) = item.node {
82 match consts::trans_static(&ccx, m, item.id, &item.attrs) {
83 Ok(_) => { /* Cool, everything's alright. */ },
85 err.report(tcx, item.span, "static");
89 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
92 TransItem::GlobalAsm(node_id) => {
93 let item = ccx.tcx().hir.expect_item(node_id);
94 if let hir::ItemGlobalAsm(ref ga) = item.node {
95 asm::trans_global_asm(ccx, ga);
97 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
100 TransItem::Fn(instance) => {
101 base::trans_instance(&ccx, instance);
105 debug!("END IMPLEMENTING '{} ({})' in cgu {}",
106 self.to_string(ccx.tcx()),
107 self.to_raw_string(),
108 ccx.codegen_unit().name());
112 ccx: &CrateContext<'a, 'tcx>,
114 visibility: Visibility) {
115 debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
116 self.to_string(ccx.tcx()),
117 self.to_raw_string(),
118 ccx.codegen_unit().name());
120 let symbol_name = self.symbol_name(ccx.tcx());
122 debug!("symbol {}", &symbol_name);
124 match *self.as_trans_item() {
125 TransItem::Static(node_id) => {
126 predefine_static(ccx, node_id, linkage, visibility, &symbol_name);
128 TransItem::Fn(instance) => {
129 predefine_fn(ccx, instance, linkage, visibility, &symbol_name);
131 TransItem::GlobalAsm(..) => {}
134 debug!("END PREDEFINING '{} ({})' in cgu {}",
135 self.to_string(ccx.tcx()),
136 self.to_raw_string(),
137 ccx.codegen_unit().name());
140 fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
141 match *self.as_trans_item() {
142 TransItem::Fn(instance) => tcx.symbol_name(instance),
143 TransItem::Static(node_id) => {
144 let def_id = tcx.hir.local_def_id(node_id);
145 tcx.symbol_name(Instance::mono(tcx, def_id))
147 TransItem::GlobalAsm(node_id) => {
148 let def_id = tcx.hir.local_def_id(node_id);
150 name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_str()
156 fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
157 match *self.as_trans_item() {
158 TransItem::Fn(Instance { def, .. }) => {
159 tcx.hir.as_local_node_id(def.def_id())
161 TransItem::Static(node_id) |
162 TransItem::GlobalAsm(node_id) => {
165 }.map(|node_id| tcx.hir.span(node_id))
168 fn instantiation_mode(&self,
169 tcx: TyCtxt<'a, 'tcx, 'tcx>)
170 -> InstantiationMode {
171 let inline_in_all_cgus =
172 tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
173 tcx.sess.opts.optimize != OptLevel::No
176 match *self.as_trans_item() {
177 TransItem::Fn(ref instance) => {
178 if self.explicit_linkage(tcx).is_none() &&
179 common::requests_inline(tcx, instance)
181 if inline_in_all_cgus {
182 InstantiationMode::LocalCopy
184 InstantiationMode::GloballyShared { may_conflict: true }
187 InstantiationMode::GloballyShared { may_conflict: false }
190 TransItem::Static(..) => {
191 InstantiationMode::GloballyShared { may_conflict: false }
193 TransItem::GlobalAsm(..) => {
194 InstantiationMode::GloballyShared { may_conflict: false }
199 fn is_generic_fn(&self) -> bool {
200 match *self.as_trans_item() {
201 TransItem::Fn(ref instance) => {
202 instance.substs.types().next().is_some()
204 TransItem::Static(..) |
205 TransItem::GlobalAsm(..) => false,
209 fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Linkage> {
210 let def_id = match *self.as_trans_item() {
211 TransItem::Fn(ref instance) => instance.def_id(),
212 TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
213 TransItem::GlobalAsm(..) => return None,
216 let attributes = tcx.get_attrs(def_id);
217 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
218 if let Some(linkage) = base::linkage_by_name(&name.as_str()) {
221 let span = tcx.hir.span_if_local(def_id);
222 if let Some(span) = span {
223 tcx.sess.span_fatal(span, "invalid linkage specified")
225 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
233 /// Returns whether this instance is instantiable - whether it has no unsatisfied
236 /// In order to translate an item, all of its predicates must hold, because
237 /// otherwise the item does not make sense. Type-checking ensures that
238 /// the predicates of every item that is *used by* a valid item *do*
239 /// hold, so we can rely on that.
241 /// However, we translate collector roots (reachable items) and functions
242 /// in vtables when they are seen, even if they are not used, and so they
243 /// might not be instantiable. For example, a programmer can define this
246 /// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
247 /// <&mut () as Clone>::clone(&s);
250 /// That function can't be translated, because the method `<&mut () as Clone>::clone`
251 /// does not exist. Luckily for us, that function can't ever be used,
252 /// because that would require for `&'a mut (): Clone` to hold, so we
253 /// can just not emit any code, or even a linker reference for it.
255 /// Similarly, if a vtable method has such a signature, and therefore can't
256 /// be used, we can just not emit it and have a placeholder (a null pointer,
257 /// which will never be accessed) in its place.
258 fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
259 debug!("is_instantiable({:?})", self);
260 let (def_id, substs) = match *self.as_trans_item() {
261 TransItem::Fn(ref instance) => (instance.def_id(), instance.substs),
262 TransItem::Static(node_id) => (tcx.hir.local_def_id(node_id), Substs::empty()),
263 // global asm never has predicates
264 TransItem::GlobalAsm(..) => return true
267 let predicates = tcx.predicates_of(def_id).predicates.subst(tcx, substs);
268 traits::normalize_and_test_predicates(tcx, predicates)
271 fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
272 let hir_map = &tcx.hir;
274 return match *self.as_trans_item() {
275 TransItem::Fn(instance) => {
276 to_string_internal(tcx, "fn ", instance)
278 TransItem::Static(node_id) => {
279 let def_id = hir_map.local_def_id(node_id);
280 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
281 to_string_internal(tcx, "static ", instance)
283 TransItem::GlobalAsm(..) => {
284 "global_asm".to_string()
288 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
290 instance: Instance<'tcx>)
292 let mut result = String::with_capacity(32);
293 result.push_str(prefix);
294 let printer = DefPathBasedNames::new(tcx, false, false);
295 printer.push_instance_as_string(instance, &mut result);
300 fn to_raw_string(&self) -> String {
301 match *self.as_trans_item() {
302 TransItem::Fn(instance) => {
303 format!("Fn({:?}, {})",
305 instance.substs.as_ptr() as usize)
307 TransItem::Static(id) => {
308 format!("Static({:?})", id)
310 TransItem::GlobalAsm(id) => {
311 format!("GlobalAsm({:?})", id)
317 impl<'a, 'tcx> TransItemExt<'a, 'tcx> for TransItem<'tcx> {
318 fn as_trans_item(&self) -> &TransItem<'tcx> {
323 fn predefine_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
324 node_id: ast::NodeId,
326 visibility: Visibility,
328 let def_id = ccx.tcx().hir.local_def_id(node_id);
329 let instance = Instance::mono(ccx.tcx(), def_id);
330 let ty = common::instance_ty(ccx.tcx(), &instance);
331 let llty = type_of::type_of(ccx, ty);
333 let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
334 ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
335 &format!("symbol `{}` is already defined", symbol_name))
339 llvm::LLVMRustSetLinkage(g, base::linkage_to_llvm(linkage));
340 llvm::LLVMRustSetVisibility(g, base::visibility_to_llvm(visibility));
343 ccx.instances().borrow_mut().insert(instance, g);
344 ccx.statics().borrow_mut().insert(g, def_id);
347 fn predefine_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
348 instance: Instance<'tcx>,
350 visibility: Visibility,
352 assert!(!instance.substs.needs_infer() &&
353 !instance.substs.has_param_types());
355 let mono_ty = common::instance_ty(ccx.tcx(), &instance);
356 let attrs = instance.def.attrs(ccx.tcx());
357 let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
358 unsafe { llvm::LLVMRustSetLinkage(lldecl, base::linkage_to_llvm(linkage)) };
359 base::set_link_section(ccx, lldecl, &attrs);
360 if linkage == Linkage::LinkOnceODR ||
361 linkage == Linkage::WeakODR {
362 llvm::SetUniqueComdat(ccx.llmod(), lldecl);
365 // If we're compiling the compiler-builtins crate, e.g. the equivalent of
366 // compiler-rt, then we want to implicitly compile everything with hidden
367 // visibility as we're going to link this object all over the place but
368 // don't want the symbols to get exported.
369 if linkage != Linkage::Internal && linkage != Linkage::Private &&
370 attr::contains_name(ccx.tcx().hir.krate_attrs(), "compiler_builtins") {
372 llvm::LLVMRustSetVisibility(lldecl, llvm::Visibility::Hidden);
376 llvm::LLVMRustSetVisibility(lldecl, base::visibility_to_llvm(visibility));
380 debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
381 if common::is_inline_instance(ccx.tcx(), &instance) {
382 attributes::inline(lldecl, attributes::InlineAttr::Hint);
384 attributes::from_fn_attrs(ccx, &attrs, lldecl);
386 ccx.instances().borrow_mut().insert(instance, lldecl);
389 //=-----------------------------------------------------------------------------
390 // TransItem String Keys
391 //=-----------------------------------------------------------------------------
393 // The code below allows for producing a unique string key for a trans item.
394 // These keys are used by the handwritten auto-tests, so they need to be
395 // predictable and human-readable.
397 // Note: A lot of this could looks very similar to what's already in the
398 // ppaux module. It would be good to refactor things so we only have one
399 // parameterizable implementation for printing types.
401 /// Same as `unique_type_name()` but with the result pushed onto the given
402 /// `output` parameter.
403 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
404 tcx: TyCtxt<'a, 'tcx, 'tcx>,
405 omit_disambiguators: bool,
406 omit_local_crate_name: bool,
409 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
410 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
411 omit_disambiguators: bool,
412 omit_local_crate_name: bool)
417 omit_local_crate_name,
421 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
423 ty::TyBool => output.push_str("bool"),
424 ty::TyChar => output.push_str("char"),
425 ty::TyStr => output.push_str("str"),
426 ty::TyNever => output.push_str("!"),
427 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
428 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
429 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
430 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
431 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
432 ty::TyInt(ast::IntTy::I128) => output.push_str("i128"),
433 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
434 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
435 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
436 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
437 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
438 ty::TyUint(ast::UintTy::U128) => output.push_str("u128"),
439 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
440 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
441 ty::TyAdt(adt_def, substs) => {
442 self.push_def_path(adt_def.did, output);
443 self.push_type_params(substs, iter::empty(), output);
445 ty::TyTuple(component_types, _) => {
447 for &component_type in component_types {
448 self.push_type_name(component_type, output);
449 output.push_str(", ");
451 if !component_types.is_empty() {
457 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
460 hir::MutImmutable => output.push_str("const "),
461 hir::MutMutable => output.push_str("mut "),
464 self.push_type_name(inner_type, output);
466 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
468 if mutbl == hir::MutMutable {
469 output.push_str("mut ");
472 self.push_type_name(inner_type, output);
474 ty::TyArray(inner_type, len) => {
476 self.push_type_name(inner_type, output);
477 write!(output, "; {}",
478 len.val.to_const_int().unwrap().to_u64().unwrap()).unwrap();
481 ty::TySlice(inner_type) => {
483 self.push_type_name(inner_type, output);
486 ty::TyDynamic(ref trait_data, ..) => {
487 if let Some(principal) = trait_data.principal() {
488 self.push_def_path(principal.def_id(), output);
489 self.push_type_params(principal.skip_binder().substs,
490 trait_data.projection_bounds(),
496 let sig = t.fn_sig(self.tcx);
497 if sig.unsafety() == hir::Unsafety::Unsafe {
498 output.push_str("unsafe ");
502 if abi != ::abi::Abi::Rust {
503 output.push_str("extern \"");
504 output.push_str(abi.name());
505 output.push_str("\" ");
508 output.push_str("fn(");
510 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
512 if !sig.inputs().is_empty() {
513 for ¶meter_type in sig.inputs() {
514 self.push_type_name(parameter_type, output);
515 output.push_str(", ");
522 if !sig.inputs().is_empty() {
523 output.push_str(", ...");
525 output.push_str("...");
531 if !sig.output().is_nil() {
532 output.push_str(" -> ");
533 self.push_type_name(sig.output(), output);
536 ty::TyGenerator(def_id, ref closure_substs, _) |
537 ty::TyClosure(def_id, ref closure_substs) => {
538 self.push_def_path(def_id, output);
539 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
540 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
541 self.push_type_params(substs, iter::empty(), output);
545 ty::TyProjection(..) |
548 bug!("DefPathBasedNames: Trying to create type name for \
549 unexpected type: {:?}", t);
554 pub fn push_def_path(&self,
556 output: &mut String) {
557 let def_path = self.tcx.def_path(def_id);
560 if !(self.omit_local_crate_name && def_id.is_local()) {
561 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
562 output.push_str("::");
565 // foo::bar::ItemName::
566 for part in self.tcx.def_path(def_id).data {
567 if self.omit_disambiguators {
568 write!(output, "{}::", part.data.as_interned_str()).unwrap();
570 write!(output, "{}[{}]::",
571 part.data.as_interned_str(),
572 part.disambiguator).unwrap();
581 fn push_type_params<I>(&self,
582 substs: &Substs<'tcx>,
585 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
587 let mut projections = projections.peekable();
588 if substs.types().next().is_none() && projections.peek().is_none() {
594 for type_parameter in substs.types() {
595 self.push_type_name(type_parameter, output);
596 output.push_str(", ");
599 for projection in projections {
600 let projection = projection.skip_binder();
601 let name = &self.tcx.associated_item(projection.item_def_id).name.as_str();
602 output.push_str(name);
603 output.push_str("=");
604 self.push_type_name(projection.ty, output);
605 output.push_str(", ");
614 pub fn push_instance_as_string(&self,
615 instance: Instance<'tcx>,
616 output: &mut String) {
617 self.push_def_path(instance.def_id(), output);
618 self.push_type_params(instance.substs, iter::empty(), output);