]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
introduce the rather simpler symbol-cache in place of symbol-map
[rust.git] / src / librustc_trans / trans_item.rs
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.
4 //
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.
10
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.
16
17 use asm;
18 use attributes;
19 use base;
20 use consts;
21 use context::{CrateContext, SharedCrateContext};
22 use common;
23 use declare;
24 use llvm;
25 use monomorphize::Instance;
26 use rustc::dep_graph::DepNode;
27 use rustc::hir;
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};
32 use syntax::attr;
33 use type_of;
34 use back::symbol_names;
35 use std::fmt::Write;
36 use std::iter;
37
38 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
39 pub enum TransItem<'tcx> {
40     Fn(Instance<'tcx>),
41     Static(NodeId),
42     GlobalAsm(NodeId),
43 }
44
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.
50     GloballyShared,
51
52     /// Each codegen unit containing a reference to the given TransItem will
53     /// have its own private copy of the function (with internal linkage).
54     LocalCopy,
55 }
56
57 impl<'a, 'tcx> TransItem<'tcx> {
58
59     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
60         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
61                   self.to_string(ccx.tcx()),
62                   self.to_raw_string(),
63                   ccx.codegen_unit().name());
64
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
73         // particular set.
74
75         match *self {
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. */ },
83                         Err(err) => {
84                             err.report(ccx.tcx(), item.span, "static");
85                         }
86                     };
87                 } else {
88                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
89                 }
90             }
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);
95                 } else {
96                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
97                 }
98             }
99             TransItem::Fn(instance) => {
100                 let _task = ccx.tcx().dep_graph.in_task(
101                     DepNode::TransCrateItem(instance.def_id())); // (*)
102
103                 base::trans_instance(&ccx, instance);
104             }
105         }
106
107         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
108                self.to_string(ccx.tcx()),
109                self.to_raw_string(),
110                ccx.codegen_unit().name());
111     }
112
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());
120
121         let symbol_name = ccx.symbol_cache().get(*self);
122
123         debug!("symbol {}", &symbol_name);
124
125         match *self {
126             TransItem::Static(node_id) => {
127                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
128             }
129             TransItem::Fn(instance) => {
130                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
131             }
132             TransItem::GlobalAsm(..) => {}
133         }
134
135         debug!("END PREDEFINING '{} ({})' in cgu {}",
136                self.to_string(ccx.tcx()),
137                self.to_raw_string(),
138                ccx.codegen_unit().name());
139     }
140
141     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
142                         node_id: ast::NodeId,
143                         linkage: llvm::Linkage,
144                         symbol_name: &str) {
145         let def_id = ccx.tcx().hir.local_def_id(node_id);
146         let instance = Instance::mono(ccx.tcx(), def_id);
147         let ty = common::instance_ty(ccx.shared(), &instance);
148         let llty = type_of::type_of(ccx, ty);
149
150         let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
151             ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
152                 &format!("symbol `{}` is already defined", symbol_name))
153         });
154
155         unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
156
157         ccx.instances().borrow_mut().insert(instance, g);
158         ccx.statics().borrow_mut().insert(g, def_id);
159     }
160
161     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
162                     instance: Instance<'tcx>,
163                     linkage: llvm::Linkage,
164                     symbol_name: &str) {
165         assert!(!instance.substs.needs_infer() &&
166                 !instance.substs.has_param_types());
167
168         let mono_ty = common::instance_ty(ccx.shared(), &instance);
169         let attrs = instance.def.attrs(ccx.tcx());
170         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
171         unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
172         base::set_link_section(ccx, lldecl, &attrs);
173         if linkage == llvm::Linkage::LinkOnceODRLinkage ||
174             linkage == llvm::Linkage::WeakODRLinkage {
175             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
176         }
177
178         debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
179         if common::is_inline_instance(ccx.tcx(), &instance) {
180             attributes::inline(lldecl, attributes::InlineAttr::Hint);
181         }
182         attributes::from_fn_attrs(ccx, &attrs, lldecl);
183
184         ccx.instances().borrow_mut().insert(instance, lldecl);
185     }
186
187     pub fn compute_symbol_name(&self,
188                                scx: &SharedCrateContext<'a, 'tcx>) -> String {
189         match *self {
190             TransItem::Fn(instance) => symbol_names::symbol_name(instance, scx),
191             TransItem::Static(node_id) => {
192                 let def_id = scx.tcx().hir.local_def_id(node_id);
193                 symbol_names::symbol_name(Instance::mono(scx.tcx(), def_id), scx)
194             }
195             TransItem::GlobalAsm(node_id) => {
196                 let def_id = scx.tcx().hir.local_def_id(node_id);
197                 format!("global_asm_{:?}", def_id)
198             }
199         }
200     }
201
202     pub fn instantiation_mode(&self,
203                               tcx: TyCtxt<'a, 'tcx, 'tcx>)
204                               -> InstantiationMode {
205         match *self {
206             TransItem::Fn(ref instance) => {
207                 if self.explicit_linkage(tcx).is_none() &&
208                     common::requests_inline(tcx, instance)
209                 {
210                     InstantiationMode::LocalCopy
211                 } else {
212                     InstantiationMode::GloballyShared
213                 }
214             }
215             TransItem::Static(..) => InstantiationMode::GloballyShared,
216             TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
217         }
218     }
219
220     pub fn is_generic_fn(&self) -> bool {
221         match *self {
222             TransItem::Fn(ref instance) => {
223                 instance.substs.types().next().is_some()
224             }
225             TransItem::Static(..) |
226             TransItem::GlobalAsm(..) => false,
227         }
228     }
229
230     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
231         let def_id = match *self {
232             TransItem::Fn(ref instance) => instance.def_id(),
233             TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
234             TransItem::GlobalAsm(..) => return None,
235         };
236
237         let attributes = tcx.get_attrs(def_id);
238         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
239             if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
240                 Some(linkage)
241             } else {
242                 let span = tcx.hir.span_if_local(def_id);
243                 if let Some(span) = span {
244                     tcx.sess.span_fatal(span, "invalid linkage specified")
245                 } else {
246                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
247                 }
248             }
249         } else {
250             None
251         }
252     }
253
254     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
255         let hir_map = &tcx.hir;
256
257         return match *self {
258             TransItem::Fn(instance) => {
259                 to_string_internal(tcx, "fn ", instance)
260             },
261             TransItem::Static(node_id) => {
262                 let def_id = hir_map.local_def_id(node_id);
263                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
264                 to_string_internal(tcx, "static ", instance)
265             },
266             TransItem::GlobalAsm(..) => {
267                 "global_asm".to_string()
268             }
269         };
270
271         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
272                                         prefix: &str,
273                                         instance: Instance<'tcx>)
274                                         -> String {
275             let mut result = String::with_capacity(32);
276             result.push_str(prefix);
277             let printer = DefPathBasedNames::new(tcx, false, false);
278             printer.push_instance_as_string(instance, &mut result);
279             result
280         }
281     }
282
283     pub fn to_raw_string(&self) -> String {
284         match *self {
285             TransItem::Fn(instance) => {
286                 format!("Fn({:?}, {})",
287                          instance.def,
288                          instance.substs.as_ptr() as usize)
289             }
290             TransItem::Static(id) => {
291                 format!("Static({:?})", id)
292             }
293             TransItem::GlobalAsm(id) => {
294                 format!("GlobalAsm({:?})", id)
295             }
296         }
297     }
298 }
299
300
301 //=-----------------------------------------------------------------------------
302 // TransItem String Keys
303 //=-----------------------------------------------------------------------------
304
305 // The code below allows for producing a unique string key for a trans item.
306 // These keys are used by the handwritten auto-tests, so they need to be
307 // predictable and human-readable.
308 //
309 // Note: A lot of this could looks very similar to what's already in the
310 //       ppaux module. It would be good to refactor things so we only have one
311 //       parameterizable implementation for printing types.
312
313 /// Same as `unique_type_name()` but with the result pushed onto the given
314 /// `output` parameter.
315 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
316     tcx: TyCtxt<'a, 'tcx, 'tcx>,
317     omit_disambiguators: bool,
318     omit_local_crate_name: bool,
319 }
320
321 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
322     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
323                omit_disambiguators: bool,
324                omit_local_crate_name: bool)
325                -> Self {
326         DefPathBasedNames {
327             tcx: tcx,
328             omit_disambiguators: omit_disambiguators,
329             omit_local_crate_name: omit_local_crate_name,
330         }
331     }
332
333     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
334         match t.sty {
335             ty::TyBool              => output.push_str("bool"),
336             ty::TyChar              => output.push_str("char"),
337             ty::TyStr               => output.push_str("str"),
338             ty::TyNever             => output.push_str("!"),
339             ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
340             ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
341             ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
342             ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
343             ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
344             ty::TyInt(ast::IntTy::I128)   => output.push_str("i128"),
345             ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
346             ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
347             ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
348             ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
349             ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
350             ty::TyUint(ast::UintTy::U128)  => output.push_str("u128"),
351             ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
352             ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
353             ty::TyAdt(adt_def, substs) => {
354                 self.push_def_path(adt_def.did, output);
355                 self.push_type_params(substs, iter::empty(), output);
356             },
357             ty::TyTuple(component_types, _) => {
358                 output.push('(');
359                 for &component_type in component_types {
360                     self.push_type_name(component_type, output);
361                     output.push_str(", ");
362                 }
363                 if !component_types.is_empty() {
364                     output.pop();
365                     output.pop();
366                 }
367                 output.push(')');
368             },
369             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
370                 output.push('*');
371                 match mutbl {
372                     hir::MutImmutable => output.push_str("const "),
373                     hir::MutMutable => output.push_str("mut "),
374                 }
375
376                 self.push_type_name(inner_type, output);
377             },
378             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
379                 output.push('&');
380                 if mutbl == hir::MutMutable {
381                     output.push_str("mut ");
382                 }
383
384                 self.push_type_name(inner_type, output);
385             },
386             ty::TyArray(inner_type, len) => {
387                 output.push('[');
388                 self.push_type_name(inner_type, output);
389                 write!(output, "; {}", len).unwrap();
390                 output.push(']');
391             },
392             ty::TySlice(inner_type) => {
393                 output.push('[');
394                 self.push_type_name(inner_type, output);
395                 output.push(']');
396             },
397             ty::TyDynamic(ref trait_data, ..) => {
398                 if let Some(principal) = trait_data.principal() {
399                     self.push_def_path(principal.def_id(), output);
400                     self.push_type_params(principal.skip_binder().substs,
401                         trait_data.projection_bounds(),
402                         output);
403                 }
404             },
405             ty::TyFnDef(.., sig) |
406             ty::TyFnPtr(sig) => {
407                 if sig.unsafety() == hir::Unsafety::Unsafe {
408                     output.push_str("unsafe ");
409                 }
410
411                 let abi = sig.abi();
412                 if abi != ::abi::Abi::Rust {
413                     output.push_str("extern \"");
414                     output.push_str(abi.name());
415                     output.push_str("\" ");
416                 }
417
418                 output.push_str("fn(");
419
420                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
421
422                 if !sig.inputs().is_empty() {
423                     for &parameter_type in sig.inputs() {
424                         self.push_type_name(parameter_type, output);
425                         output.push_str(", ");
426                     }
427                     output.pop();
428                     output.pop();
429                 }
430
431                 if sig.variadic {
432                     if !sig.inputs().is_empty() {
433                         output.push_str(", ...");
434                     } else {
435                         output.push_str("...");
436                     }
437                 }
438
439                 output.push(')');
440
441                 if !sig.output().is_nil() {
442                     output.push_str(" -> ");
443                     self.push_type_name(sig.output(), output);
444                 }
445             },
446             ty::TyClosure(def_id, ref closure_substs) => {
447                 self.push_def_path(def_id, output);
448                 let generics = self.tcx.item_generics(self.tcx.closure_base_def_id(def_id));
449                 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
450                 self.push_type_params(substs, iter::empty(), output);
451             }
452             ty::TyError |
453             ty::TyInfer(_) |
454             ty::TyProjection(..) |
455             ty::TyParam(_) |
456             ty::TyAnon(..) => {
457                 bug!("DefPathBasedNames: Trying to create type name for \
458                                          unexpected type: {:?}", t);
459             }
460         }
461     }
462
463     pub fn push_def_path(&self,
464                          def_id: DefId,
465                          output: &mut String) {
466         let def_path = self.tcx.def_path(def_id);
467
468         // some_crate::
469         if !(self.omit_local_crate_name && def_id.is_local()) {
470             output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
471             output.push_str("::");
472         }
473
474         // foo::bar::ItemName::
475         for part in self.tcx.def_path(def_id).data {
476             if self.omit_disambiguators {
477                 write!(output, "{}::", part.data.as_interned_str()).unwrap();
478             } else {
479                 write!(output, "{}[{}]::",
480                        part.data.as_interned_str(),
481                        part.disambiguator).unwrap();
482             }
483         }
484
485         // remove final "::"
486         output.pop();
487         output.pop();
488     }
489
490     fn push_type_params<I>(&self,
491                             substs: &Substs<'tcx>,
492                             projections: I,
493                             output: &mut String)
494         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
495     {
496         let mut projections = projections.peekable();
497         if substs.types().next().is_none() && projections.peek().is_none() {
498             return;
499         }
500
501         output.push('<');
502
503         for type_parameter in substs.types() {
504             self.push_type_name(type_parameter, output);
505             output.push_str(", ");
506         }
507
508         for projection in projections {
509             let projection = projection.skip_binder();
510             let name = &projection.item_name.as_str();
511             output.push_str(name);
512             output.push_str("=");
513             self.push_type_name(projection.ty, output);
514             output.push_str(", ");
515         }
516
517         output.pop();
518         output.pop();
519
520         output.push('>');
521     }
522
523     pub fn push_instance_as_string(&self,
524                                    instance: Instance<'tcx>,
525                                    output: &mut String) {
526         self.push_def_path(instance.def_id(), output);
527         self.push_type_params(instance.substs, iter::empty(), output);
528     }
529 }