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, SharedCrateContext};
25 use monomorphize::Instance;
26 use rustc::dep_graph::DepNode;
28 use rustc::hir::def_id::DefId;
29 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
30 use rustc::ty::subst::Substs;
31 use syntax::ast::{self, NodeId};
34 use back::symbol_names;
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());
65 // (*) This code executes in the context of a dep-node for the
66 // entire CGU. In some cases, we introduce dep-nodes for
67 // particular items that we are translating (these nodes will
68 // have read edges coming into the CGU node). These smaller
69 // nodes are not needed for correctness -- we always
70 // invalidate an entire CGU at a time -- but they enable
71 // finer-grained testing, since you can write tests that check
72 // that the incoming edges to a particular fn are from a
76 TransItem::Static(node_id) => {
77 let def_id = ccx.tcx().hir.local_def_id(node_id);
78 let _task = ccx.tcx().dep_graph.in_task(DepNode::TransCrateItem(def_id)); // (*)
79 let item = ccx.tcx().hir.expect_item(node_id);
80 if let hir::ItemStatic(_, m, _) = item.node {
81 match consts::trans_static(&ccx, m, item.id, &item.attrs) {
82 Ok(_) => { /* Cool, everything's alright. */ },
84 err.report(ccx.tcx(), item.span, "static");
88 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
91 TransItem::GlobalAsm(node_id) => {
92 let item = ccx.tcx().hir.expect_item(node_id);
93 if let hir::ItemGlobalAsm(ref ga) = item.node {
94 asm::trans_global_asm(ccx, ga);
96 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
99 TransItem::Fn(instance) => {
100 let _task = ccx.tcx().dep_graph.in_task(
101 DepNode::TransCrateItem(instance.def_id())); // (*)
103 base::trans_instance(&ccx, instance);
107 debug!("END IMPLEMENTING '{} ({})' in cgu {}",
108 self.to_string(ccx.tcx()),
109 self.to_raw_string(),
110 ccx.codegen_unit().name());
113 pub fn predefine(&self,
114 ccx: &CrateContext<'a, 'tcx>,
115 linkage: llvm::Linkage) {
116 debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
117 self.to_string(ccx.tcx()),
118 self.to_raw_string(),
119 ccx.codegen_unit().name());
121 let symbol_name = ccx.symbol_map()
122 .get_or_compute(ccx.shared(), *self);
124 debug!("symbol {}", &symbol_name);
127 TransItem::Static(node_id) => {
128 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
130 TransItem::Fn(instance) => {
131 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
133 TransItem::GlobalAsm(..) => {}
136 debug!("END PREDEFINING '{} ({})' in cgu {}",
137 self.to_string(ccx.tcx()),
138 self.to_raw_string(),
139 ccx.codegen_unit().name());
142 fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
143 node_id: ast::NodeId,
144 linkage: llvm::Linkage,
146 let def_id = ccx.tcx().hir.local_def_id(node_id);
147 let instance = Instance::mono(ccx.tcx(), def_id);
148 let ty = common::instance_ty(ccx.shared(), &instance);
149 let llty = type_of::type_of(ccx, ty);
151 let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
152 ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
153 &format!("symbol `{}` is already defined", symbol_name))
156 unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
158 ccx.instances().borrow_mut().insert(instance, g);
159 ccx.statics().borrow_mut().insert(g, def_id);
162 fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
163 instance: Instance<'tcx>,
164 linkage: llvm::Linkage,
166 assert!(!instance.substs.needs_infer() &&
167 !instance.substs.has_param_types());
169 let mono_ty = common::instance_ty(ccx.shared(), &instance);
170 let attrs = instance.def.attrs(ccx.tcx());
171 let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
172 unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
173 base::set_link_section(ccx, lldecl, &attrs);
174 if linkage == llvm::Linkage::LinkOnceODRLinkage ||
175 linkage == llvm::Linkage::WeakODRLinkage {
176 llvm::SetUniqueComdat(ccx.llmod(), lldecl);
179 debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
180 if common::is_inline_instance(ccx.tcx(), &instance) {
181 attributes::inline(lldecl, attributes::InlineAttr::Hint);
183 attributes::from_fn_attrs(ccx, &attrs, lldecl);
185 ccx.instances().borrow_mut().insert(instance, lldecl);
188 pub fn compute_symbol_name(&self,
189 scx: &SharedCrateContext<'a, 'tcx>) -> String {
191 TransItem::Fn(instance) => symbol_names::symbol_name(instance, scx),
192 TransItem::Static(node_id) => {
193 let def_id = scx.tcx().hir.local_def_id(node_id);
194 symbol_names::symbol_name(Instance::mono(scx.tcx(), def_id), scx)
196 TransItem::GlobalAsm(node_id) => {
197 let def_id = scx.tcx().hir.local_def_id(node_id);
198 format!("global_asm_{:?}", def_id)
203 pub fn instantiation_mode(&self,
204 tcx: TyCtxt<'a, 'tcx, 'tcx>)
205 -> InstantiationMode {
207 TransItem::Fn(ref instance) => {
208 if self.explicit_linkage(tcx).is_none() &&
209 common::requests_inline(tcx, instance)
211 InstantiationMode::LocalCopy
213 InstantiationMode::GloballyShared
216 TransItem::Static(..) => InstantiationMode::GloballyShared,
217 TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
221 pub fn is_generic_fn(&self) -> bool {
223 TransItem::Fn(ref instance) => {
224 instance.substs.types().next().is_some()
226 TransItem::Static(..) |
227 TransItem::GlobalAsm(..) => false,
231 pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
232 let def_id = match *self {
233 TransItem::Fn(ref instance) => instance.def_id(),
234 TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
235 TransItem::GlobalAsm(..) => return None,
238 let attributes = tcx.get_attrs(def_id);
239 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
240 if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
243 let span = tcx.hir.span_if_local(def_id);
244 if let Some(span) = span {
245 tcx.sess.span_fatal(span, "invalid linkage specified")
247 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
255 pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
256 let hir_map = &tcx.hir;
259 TransItem::Fn(instance) => {
260 to_string_internal(tcx, "fn ", instance)
262 TransItem::Static(node_id) => {
263 let def_id = hir_map.local_def_id(node_id);
264 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
265 to_string_internal(tcx, "static ", instance)
267 TransItem::GlobalAsm(..) => {
268 "global_asm".to_string()
272 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
274 instance: Instance<'tcx>)
276 let mut result = String::with_capacity(32);
277 result.push_str(prefix);
278 let printer = DefPathBasedNames::new(tcx, false, false);
279 printer.push_instance_as_string(instance, &mut result);
284 pub fn to_raw_string(&self) -> String {
286 TransItem::Fn(instance) => {
287 format!("Fn({:?}, {})",
289 instance.substs.as_ptr() as usize)
291 TransItem::Static(id) => {
292 format!("Static({:?})", id)
294 TransItem::GlobalAsm(id) => {
295 format!("GlobalAsm({:?})", id)
302 //=-----------------------------------------------------------------------------
303 // TransItem String Keys
304 //=-----------------------------------------------------------------------------
306 // The code below allows for producing a unique string key for a trans item.
307 // These keys are used by the handwritten auto-tests, so they need to be
308 // predictable and human-readable.
310 // Note: A lot of this could looks very similar to what's already in the
311 // ppaux module. It would be good to refactor things so we only have one
312 // parameterizable implementation for printing types.
314 /// Same as `unique_type_name()` but with the result pushed onto the given
315 /// `output` parameter.
316 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
317 tcx: TyCtxt<'a, 'tcx, 'tcx>,
318 omit_disambiguators: bool,
319 omit_local_crate_name: bool,
322 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
323 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
324 omit_disambiguators: bool,
325 omit_local_crate_name: bool)
329 omit_disambiguators: omit_disambiguators,
330 omit_local_crate_name: omit_local_crate_name,
334 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
336 ty::TyBool => output.push_str("bool"),
337 ty::TyChar => output.push_str("char"),
338 ty::TyStr => output.push_str("str"),
339 ty::TyNever => output.push_str("!"),
340 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
341 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
342 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
343 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
344 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
345 ty::TyInt(ast::IntTy::I128) => output.push_str("i128"),
346 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
347 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
348 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
349 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
350 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
351 ty::TyUint(ast::UintTy::U128) => output.push_str("u128"),
352 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
353 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
354 ty::TyAdt(adt_def, substs) => {
355 self.push_def_path(adt_def.did, output);
356 self.push_type_params(substs, iter::empty(), output);
358 ty::TyTuple(component_types, _) => {
360 for &component_type in component_types {
361 self.push_type_name(component_type, output);
362 output.push_str(", ");
364 if !component_types.is_empty() {
370 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
373 hir::MutImmutable => output.push_str("const "),
374 hir::MutMutable => output.push_str("mut "),
377 self.push_type_name(inner_type, output);
379 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
381 if mutbl == hir::MutMutable {
382 output.push_str("mut ");
385 self.push_type_name(inner_type, output);
387 ty::TyArray(inner_type, len) => {
389 self.push_type_name(inner_type, output);
390 write!(output, "; {}", len).unwrap();
393 ty::TySlice(inner_type) => {
395 self.push_type_name(inner_type, output);
398 ty::TyDynamic(ref trait_data, ..) => {
399 if let Some(principal) = trait_data.principal() {
400 self.push_def_path(principal.def_id(), output);
401 self.push_type_params(principal.skip_binder().substs,
402 trait_data.projection_bounds(),
406 ty::TyFnDef(.., sig) |
407 ty::TyFnPtr(sig) => {
408 if sig.unsafety() == hir::Unsafety::Unsafe {
409 output.push_str("unsafe ");
413 if abi != ::abi::Abi::Rust {
414 output.push_str("extern \"");
415 output.push_str(abi.name());
416 output.push_str("\" ");
419 output.push_str("fn(");
421 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
423 if !sig.inputs().is_empty() {
424 for ¶meter_type in sig.inputs() {
425 self.push_type_name(parameter_type, output);
426 output.push_str(", ");
433 if !sig.inputs().is_empty() {
434 output.push_str(", ...");
436 output.push_str("...");
442 if !sig.output().is_nil() {
443 output.push_str(" -> ");
444 self.push_type_name(sig.output(), output);
447 ty::TyClosure(def_id, ref closure_substs) => {
448 self.push_def_path(def_id, output);
449 let generics = self.tcx.item_generics(self.tcx.closure_base_def_id(def_id));
450 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
451 self.push_type_params(substs, iter::empty(), output);
455 ty::TyProjection(..) |
458 bug!("DefPathBasedNames: Trying to create type name for \
459 unexpected type: {:?}", t);
464 pub fn push_def_path(&self,
466 output: &mut String) {
467 let def_path = self.tcx.def_path(def_id);
470 if !(self.omit_local_crate_name && def_id.is_local()) {
471 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
472 output.push_str("::");
475 // foo::bar::ItemName::
476 for part in self.tcx.def_path(def_id).data {
477 if self.omit_disambiguators {
478 write!(output, "{}::", part.data.as_interned_str()).unwrap();
480 write!(output, "{}[{}]::",
481 part.data.as_interned_str(),
482 part.disambiguator).unwrap();
491 fn push_type_params<I>(&self,
492 substs: &Substs<'tcx>,
495 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
497 let mut projections = projections.peekable();
498 if substs.types().next().is_none() && projections.peek().is_none() {
504 for type_parameter in substs.types() {
505 self.push_type_name(type_parameter, output);
506 output.push_str(", ");
509 for projection in projections {
510 let projection = projection.skip_binder();
511 let name = &projection.item_name.as_str();
512 output.push_str(name);
513 output.push_str("=");
514 self.push_type_name(projection.ty, output);
515 output.push_str(", ");
524 pub fn push_instance_as_string(&self,
525 instance: Instance<'tcx>,
526 output: &mut String) {
527 self.push_def_path(instance.def_id(), output);
528 self.push_type_params(instance.substs, iter::empty(), output);