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::ty::{self, Ty, TyCtxt, TypeFoldable};
29 use rustc::ty::subst::Substs;
30 use syntax::ast::{self, NodeId};
33 use syntax_pos::symbol::Symbol;
38 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
39 pub enum TransItem<'tcx> {
45 /// Describes how a translation item will be instantiated in object files.
46 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
47 pub enum InstantiationMode {
48 /// There will be exactly one instance of the given TransItem. It will have
49 /// external linkage so that it can be linked to from other codegen units.
52 /// Each codegen unit containing a reference to the given TransItem will
53 /// have its own private copy of the function (with internal linkage).
57 impl<'a, 'tcx> TransItem<'tcx> {
59 pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
60 debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
61 self.to_string(ccx.tcx()),
63 ccx.codegen_unit().name());
66 TransItem::Static(node_id) => {
68 let item = tcx.hir.expect_item(node_id);
69 if let hir::ItemStatic(_, m, _) = item.node {
70 match consts::trans_static(&ccx, m, item.id, &item.attrs) {
71 Ok(_) => { /* Cool, everything's alright. */ },
73 err.report(tcx, item.span, "static");
77 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
80 TransItem::GlobalAsm(node_id) => {
81 let item = ccx.tcx().hir.expect_item(node_id);
82 if let hir::ItemGlobalAsm(ref ga) = item.node {
83 asm::trans_global_asm(ccx, ga);
85 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
88 TransItem::Fn(instance) => {
89 base::trans_instance(&ccx, instance);
93 debug!("END IMPLEMENTING '{} ({})' in cgu {}",
94 self.to_string(ccx.tcx()),
96 ccx.codegen_unit().name());
99 pub fn predefine(&self,
100 ccx: &CrateContext<'a, 'tcx>,
101 linkage: llvm::Linkage) {
102 debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
103 self.to_string(ccx.tcx()),
104 self.to_raw_string(),
105 ccx.codegen_unit().name());
107 let symbol_name = self.symbol_name(ccx.tcx());
109 debug!("symbol {}", &symbol_name);
112 TransItem::Static(node_id) => {
113 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
115 TransItem::Fn(instance) => {
116 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
118 TransItem::GlobalAsm(..) => {}
121 debug!("END PREDEFINING '{} ({})' in cgu {}",
122 self.to_string(ccx.tcx()),
123 self.to_raw_string(),
124 ccx.codegen_unit().name());
127 fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
128 node_id: ast::NodeId,
129 linkage: llvm::Linkage,
131 let def_id = ccx.tcx().hir.local_def_id(node_id);
132 let instance = Instance::mono(ccx.tcx(), def_id);
133 let ty = common::instance_ty(ccx.shared(), &instance);
134 let llty = type_of::type_of(ccx, ty);
136 let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
137 ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
138 &format!("symbol `{}` is already defined", symbol_name))
141 unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
143 ccx.instances().borrow_mut().insert(instance, g);
144 ccx.statics().borrow_mut().insert(g, def_id);
147 fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
148 instance: Instance<'tcx>,
149 linkage: llvm::Linkage,
151 assert!(!instance.substs.needs_infer() &&
152 !instance.substs.has_param_types());
154 let mono_ty = common::instance_ty(ccx.shared(), &instance);
155 let attrs = instance.def.attrs(ccx.tcx());
156 let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
157 unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
158 base::set_link_section(ccx, lldecl, &attrs);
159 if linkage == llvm::Linkage::LinkOnceODRLinkage ||
160 linkage == llvm::Linkage::WeakODRLinkage {
161 llvm::SetUniqueComdat(ccx.llmod(), lldecl);
164 debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
165 if common::is_inline_instance(ccx.tcx(), &instance) {
166 attributes::inline(lldecl, attributes::InlineAttr::Hint);
168 attributes::from_fn_attrs(ccx, &attrs, lldecl);
170 ccx.instances().borrow_mut().insert(instance, lldecl);
173 pub fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
175 TransItem::Fn(instance) => tcx.symbol_name(instance),
176 TransItem::Static(node_id) => {
177 let def_id = tcx.hir.local_def_id(node_id);
178 tcx.symbol_name(Instance::mono(tcx, def_id))
180 TransItem::GlobalAsm(node_id) => {
181 let def_id = tcx.hir.local_def_id(node_id);
183 name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_str()
189 pub fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
191 TransItem::Fn(Instance { def, .. }) => {
192 tcx.hir.as_local_node_id(def.def_id())
194 TransItem::Static(node_id) |
195 TransItem::GlobalAsm(node_id) => {
198 }.map(|node_id| tcx.hir.span(node_id))
201 pub fn instantiation_mode(&self,
202 tcx: TyCtxt<'a, 'tcx, 'tcx>)
203 -> InstantiationMode {
205 TransItem::Fn(ref instance) => {
206 if self.explicit_linkage(tcx).is_none() &&
207 common::requests_inline(tcx, instance)
209 InstantiationMode::LocalCopy
211 InstantiationMode::GloballyShared
214 TransItem::Static(..) => InstantiationMode::GloballyShared,
215 TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
219 pub fn is_generic_fn(&self) -> bool {
221 TransItem::Fn(ref instance) => {
222 instance.substs.types().next().is_some()
224 TransItem::Static(..) |
225 TransItem::GlobalAsm(..) => false,
229 pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
230 let def_id = match *self {
231 TransItem::Fn(ref instance) => instance.def_id(),
232 TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
233 TransItem::GlobalAsm(..) => return None,
236 let attributes = tcx.get_attrs(def_id);
237 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
238 if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
241 let span = tcx.hir.span_if_local(def_id);
242 if let Some(span) = span {
243 tcx.sess.span_fatal(span, "invalid linkage specified")
245 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
253 pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
254 let hir_map = &tcx.hir;
257 TransItem::Fn(instance) => {
258 to_string_internal(tcx, "fn ", instance)
260 TransItem::Static(node_id) => {
261 let def_id = hir_map.local_def_id(node_id);
262 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
263 to_string_internal(tcx, "static ", instance)
265 TransItem::GlobalAsm(..) => {
266 "global_asm".to_string()
270 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
272 instance: Instance<'tcx>)
274 let mut result = String::with_capacity(32);
275 result.push_str(prefix);
276 let printer = DefPathBasedNames::new(tcx, false, false);
277 printer.push_instance_as_string(instance, &mut result);
282 pub fn to_raw_string(&self) -> String {
284 TransItem::Fn(instance) => {
285 format!("Fn({:?}, {})",
287 instance.substs.as_ptr() as usize)
289 TransItem::Static(id) => {
290 format!("Static({:?})", id)
292 TransItem::GlobalAsm(id) => {
293 format!("GlobalAsm({:?})", id)
300 //=-----------------------------------------------------------------------------
301 // TransItem String Keys
302 //=-----------------------------------------------------------------------------
304 // The code below allows for producing a unique string key for a trans item.
305 // These keys are used by the handwritten auto-tests, so they need to be
306 // predictable and human-readable.
308 // Note: A lot of this could looks very similar to what's already in the
309 // ppaux module. It would be good to refactor things so we only have one
310 // parameterizable implementation for printing types.
312 /// Same as `unique_type_name()` but with the result pushed onto the given
313 /// `output` parameter.
314 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
315 tcx: TyCtxt<'a, 'tcx, 'tcx>,
316 omit_disambiguators: bool,
317 omit_local_crate_name: bool,
320 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
321 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
322 omit_disambiguators: bool,
323 omit_local_crate_name: bool)
327 omit_disambiguators: omit_disambiguators,
328 omit_local_crate_name: omit_local_crate_name,
332 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
334 ty::TyBool => output.push_str("bool"),
335 ty::TyChar => output.push_str("char"),
336 ty::TyStr => output.push_str("str"),
337 ty::TyNever => output.push_str("!"),
338 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
339 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
340 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
341 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
342 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
343 ty::TyInt(ast::IntTy::I128) => output.push_str("i128"),
344 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
345 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
346 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
347 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
348 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
349 ty::TyUint(ast::UintTy::U128) => output.push_str("u128"),
350 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
351 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
352 ty::TyAdt(adt_def, substs) => {
353 self.push_def_path(adt_def.did, output);
354 self.push_type_params(substs, iter::empty(), output);
356 ty::TyTuple(component_types, _) => {
358 for &component_type in component_types {
359 self.push_type_name(component_type, output);
360 output.push_str(", ");
362 if !component_types.is_empty() {
368 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
371 hir::MutImmutable => output.push_str("const "),
372 hir::MutMutable => output.push_str("mut "),
375 self.push_type_name(inner_type, output);
377 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
379 if mutbl == hir::MutMutable {
380 output.push_str("mut ");
383 self.push_type_name(inner_type, output);
385 ty::TyArray(inner_type, len) => {
387 self.push_type_name(inner_type, output);
388 write!(output, "; {}", len).unwrap();
391 ty::TySlice(inner_type) => {
393 self.push_type_name(inner_type, output);
396 ty::TyDynamic(ref trait_data, ..) => {
397 if let Some(principal) = trait_data.principal() {
398 self.push_def_path(principal.def_id(), output);
399 self.push_type_params(principal.skip_binder().substs,
400 trait_data.projection_bounds(),
404 ty::TyFnDef(.., sig) |
405 ty::TyFnPtr(sig) => {
406 if sig.unsafety() == hir::Unsafety::Unsafe {
407 output.push_str("unsafe ");
411 if abi != ::abi::Abi::Rust {
412 output.push_str("extern \"");
413 output.push_str(abi.name());
414 output.push_str("\" ");
417 output.push_str("fn(");
419 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
421 if !sig.inputs().is_empty() {
422 for ¶meter_type in sig.inputs() {
423 self.push_type_name(parameter_type, output);
424 output.push_str(", ");
431 if !sig.inputs().is_empty() {
432 output.push_str(", ...");
434 output.push_str("...");
440 if !sig.output().is_nil() {
441 output.push_str(" -> ");
442 self.push_type_name(sig.output(), output);
445 ty::TyClosure(def_id, ref closure_substs) => {
446 self.push_def_path(def_id, output);
447 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
448 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
449 self.push_type_params(substs, iter::empty(), output);
453 ty::TyProjection(..) |
456 bug!("DefPathBasedNames: Trying to create type name for \
457 unexpected type: {:?}", t);
462 pub fn push_def_path(&self,
464 output: &mut String) {
465 let def_path = self.tcx.def_path(def_id);
468 if !(self.omit_local_crate_name && def_id.is_local()) {
469 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
470 output.push_str("::");
473 // foo::bar::ItemName::
474 for part in self.tcx.def_path(def_id).data {
475 if self.omit_disambiguators {
476 write!(output, "{}::", part.data.as_interned_str()).unwrap();
478 write!(output, "{}[{}]::",
479 part.data.as_interned_str(),
480 part.disambiguator).unwrap();
489 fn push_type_params<I>(&self,
490 substs: &Substs<'tcx>,
493 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
495 let mut projections = projections.peekable();
496 if substs.types().next().is_none() && projections.peek().is_none() {
502 for type_parameter in substs.types() {
503 self.push_type_name(type_parameter, output);
504 output.push_str(", ");
507 for projection in projections {
508 let projection = projection.skip_binder();
509 let name = &projection.item_name.as_str();
510 output.push_str(name);
511 output.push_str("=");
512 self.push_type_name(projection.ty, output);
513 output.push_str(", ");
522 pub fn push_instance_as_string(&self,
523 instance: Instance<'tcx>,
524 output: &mut String) {
525 self.push_def_path(instance.def_id(), output);
526 self.push_type_params(instance.substs, iter::empty(), output);