]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
run EndRegion when unwinding otherwise-empty scopes
[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;
22 use common;
23 use declare;
24 use llvm;
25 use monomorphize::Instance;
26 use rustc::hir;
27 use rustc::hir::def_id::DefId;
28 use rustc::middle::trans::{Linkage, Visibility};
29 use rustc::session::config::OptLevel;
30 use rustc::traits;
31 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
32 use rustc::ty::subst::{Subst, Substs};
33 use syntax::ast;
34 use syntax::attr;
35 use syntax_pos::Span;
36 use syntax_pos::symbol::Symbol;
37 use type_of;
38 use std::fmt::{self, Write};
39 use std::iter;
40
41 pub use rustc::middle::trans::TransItem;
42
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.
48     GloballyShared {
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.
54         ///
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.
60         may_conflict: bool,
61     },
62
63     /// Each codegen unit containing a reference to the given TransItem will
64     /// have its own private copy of the function (with internal linkage).
65     LocalCopy,
66 }
67
68 pub trait TransItemExt<'a, 'tcx>: fmt::Debug {
69     fn as_trans_item(&self) -> &TransItem<'tcx>;
70
71     fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
72         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
73                self.to_string(ccx.tcx()),
74                self.to_raw_string(),
75                ccx.codegen_unit().name());
76
77         match *self.as_trans_item() {
78             TransItem::Static(node_id) => {
79                 let tcx = ccx.tcx();
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. */ },
84                         Err(err) => {
85                             err.report(tcx, item.span, "static");
86                         }
87                     };
88                 } else {
89                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
90                 }
91             }
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);
96                 } else {
97                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
98                 }
99             }
100             TransItem::Fn(instance) => {
101                 base::trans_instance(&ccx, instance);
102             }
103         }
104
105         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
106                self.to_string(ccx.tcx()),
107                self.to_raw_string(),
108                ccx.codegen_unit().name());
109     }
110
111     fn predefine(&self,
112                  ccx: &CrateContext<'a, 'tcx>,
113                  linkage: Linkage,
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());
119
120         let symbol_name = self.symbol_name(ccx.tcx());
121
122         debug!("symbol {}", &symbol_name);
123
124         match *self.as_trans_item() {
125             TransItem::Static(node_id) => {
126                 predefine_static(ccx, node_id, linkage, visibility, &symbol_name);
127             }
128             TransItem::Fn(instance) => {
129                 predefine_fn(ccx, instance, linkage, visibility, &symbol_name);
130             }
131             TransItem::GlobalAsm(..) => {}
132         }
133
134         debug!("END PREDEFINING '{} ({})' in cgu {}",
135                self.to_string(ccx.tcx()),
136                self.to_raw_string(),
137                ccx.codegen_unit().name());
138     }
139
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))
146             }
147             TransItem::GlobalAsm(node_id) => {
148                 let def_id = tcx.hir.local_def_id(node_id);
149                 ty::SymbolName {
150                     name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_str()
151                 }
152             }
153         }
154     }
155
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())
160             }
161             TransItem::Static(node_id) |
162             TransItem::GlobalAsm(node_id) => {
163                 Some(node_id)
164             }
165         }.map(|node_id| tcx.hir.span(node_id))
166     }
167
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
174             });
175
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)
180                 {
181                     if inline_in_all_cgus {
182                         InstantiationMode::LocalCopy
183                     } else {
184                         InstantiationMode::GloballyShared  { may_conflict: true }
185                     }
186                 } else {
187                     InstantiationMode::GloballyShared  { may_conflict: false }
188                 }
189             }
190             TransItem::Static(..) => {
191                 InstantiationMode::GloballyShared { may_conflict: false }
192             }
193             TransItem::GlobalAsm(..) => {
194                 InstantiationMode::GloballyShared { may_conflict: false }
195             }
196         }
197     }
198
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()
203             }
204             TransItem::Static(..) |
205             TransItem::GlobalAsm(..) => false,
206         }
207     }
208
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,
214         };
215
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()) {
219                 Some(linkage)
220             } else {
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")
224                 } else {
225                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
226                 }
227             }
228         } else {
229             None
230         }
231     }
232
233     /// Returns whether this instance is instantiable - whether it has no unsatisfied
234     /// predicates.
235     ///
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.
240     ///
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
244     /// public function:
245     ///
246     ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
247     ///         <&mut () as Clone>::clone(&s);
248     ///     }
249     ///
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.
254     ///
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
265         };
266
267         let predicates = tcx.predicates_of(def_id).predicates.subst(tcx, substs);
268         traits::normalize_and_test_predicates(tcx, predicates)
269     }
270
271     fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
272         let hir_map = &tcx.hir;
273
274         return match *self.as_trans_item() {
275             TransItem::Fn(instance) => {
276                 to_string_internal(tcx, "fn ", instance)
277             },
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)
282             },
283             TransItem::GlobalAsm(..) => {
284                 "global_asm".to_string()
285             }
286         };
287
288         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
289                                         prefix: &str,
290                                         instance: Instance<'tcx>)
291                                         -> String {
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);
296             result
297         }
298     }
299
300     fn to_raw_string(&self) -> String {
301         match *self.as_trans_item() {
302             TransItem::Fn(instance) => {
303                 format!("Fn({:?}, {})",
304                          instance.def,
305                          instance.substs.as_ptr() as usize)
306             }
307             TransItem::Static(id) => {
308                 format!("Static({:?})", id)
309             }
310             TransItem::GlobalAsm(id) => {
311                 format!("GlobalAsm({:?})", id)
312             }
313         }
314     }
315 }
316
317 impl<'a, 'tcx> TransItemExt<'a, 'tcx> for TransItem<'tcx> {
318     fn as_trans_item(&self) -> &TransItem<'tcx> {
319         self
320     }
321 }
322
323 fn predefine_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
324                               node_id: ast::NodeId,
325                               linkage: Linkage,
326                               visibility: Visibility,
327                               symbol_name: &str) {
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);
332
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))
336     });
337
338     unsafe {
339         llvm::LLVMRustSetLinkage(g, base::linkage_to_llvm(linkage));
340         llvm::LLVMRustSetVisibility(g, base::visibility_to_llvm(visibility));
341     }
342
343     ccx.instances().borrow_mut().insert(instance, g);
344     ccx.statics().borrow_mut().insert(g, def_id);
345 }
346
347 fn predefine_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
348                           instance: Instance<'tcx>,
349                           linkage: Linkage,
350                           visibility: Visibility,
351                           symbol_name: &str) {
352     assert!(!instance.substs.needs_infer() &&
353             !instance.substs.has_param_types());
354
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);
363     }
364
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") {
371         unsafe {
372             llvm::LLVMRustSetVisibility(lldecl, llvm::Visibility::Hidden);
373         }
374     } else {
375         unsafe {
376             llvm::LLVMRustSetVisibility(lldecl, base::visibility_to_llvm(visibility));
377         }
378     }
379
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);
383     }
384     attributes::from_fn_attrs(ccx, &attrs, lldecl);
385
386     ccx.instances().borrow_mut().insert(instance, lldecl);
387 }
388
389 //=-----------------------------------------------------------------------------
390 // TransItem String Keys
391 //=-----------------------------------------------------------------------------
392
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.
396 //
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.
400
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,
407 }
408
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)
413                -> Self {
414         DefPathBasedNames {
415             tcx,
416             omit_disambiguators,
417             omit_local_crate_name,
418         }
419     }
420
421     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
422         match t.sty {
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);
444             },
445             ty::TyTuple(component_types, _) => {
446                 output.push('(');
447                 for &component_type in component_types {
448                     self.push_type_name(component_type, output);
449                     output.push_str(", ");
450                 }
451                 if !component_types.is_empty() {
452                     output.pop();
453                     output.pop();
454                 }
455                 output.push(')');
456             },
457             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
458                 output.push('*');
459                 match mutbl {
460                     hir::MutImmutable => output.push_str("const "),
461                     hir::MutMutable => output.push_str("mut "),
462                 }
463
464                 self.push_type_name(inner_type, output);
465             },
466             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
467                 output.push('&');
468                 if mutbl == hir::MutMutable {
469                     output.push_str("mut ");
470                 }
471
472                 self.push_type_name(inner_type, output);
473             },
474             ty::TyArray(inner_type, len) => {
475                 output.push('[');
476                 self.push_type_name(inner_type, output);
477                 write!(output, "; {}",
478                     len.val.to_const_int().unwrap().to_u64().unwrap()).unwrap();
479                 output.push(']');
480             },
481             ty::TySlice(inner_type) => {
482                 output.push('[');
483                 self.push_type_name(inner_type, output);
484                 output.push(']');
485             },
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(),
491                         output);
492                 }
493             },
494             ty::TyFnDef(..) |
495             ty::TyFnPtr(_) => {
496                 let sig = t.fn_sig(self.tcx);
497                 if sig.unsafety() == hir::Unsafety::Unsafe {
498                     output.push_str("unsafe ");
499                 }
500
501                 let abi = sig.abi();
502                 if abi != ::abi::Abi::Rust {
503                     output.push_str("extern \"");
504                     output.push_str(abi.name());
505                     output.push_str("\" ");
506                 }
507
508                 output.push_str("fn(");
509
510                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
511
512                 if !sig.inputs().is_empty() {
513                     for &parameter_type in sig.inputs() {
514                         self.push_type_name(parameter_type, output);
515                         output.push_str(", ");
516                     }
517                     output.pop();
518                     output.pop();
519                 }
520
521                 if sig.variadic {
522                     if !sig.inputs().is_empty() {
523                         output.push_str(", ...");
524                     } else {
525                         output.push_str("...");
526                     }
527                 }
528
529                 output.push(')');
530
531                 if !sig.output().is_nil() {
532                     output.push_str(" -> ");
533                     self.push_type_name(sig.output(), output);
534                 }
535             },
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);
542             }
543             ty::TyError |
544             ty::TyInfer(_) |
545             ty::TyProjection(..) |
546             ty::TyParam(_) |
547             ty::TyAnon(..) => {
548                 bug!("DefPathBasedNames: Trying to create type name for \
549                                          unexpected type: {:?}", t);
550             }
551         }
552     }
553
554     pub fn push_def_path(&self,
555                          def_id: DefId,
556                          output: &mut String) {
557         let def_path = self.tcx.def_path(def_id);
558
559         // some_crate::
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("::");
563         }
564
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();
569             } else {
570                 write!(output, "{}[{}]::",
571                        part.data.as_interned_str(),
572                        part.disambiguator).unwrap();
573             }
574         }
575
576         // remove final "::"
577         output.pop();
578         output.pop();
579     }
580
581     fn push_type_params<I>(&self,
582                             substs: &Substs<'tcx>,
583                             projections: I,
584                             output: &mut String)
585         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
586     {
587         let mut projections = projections.peekable();
588         if substs.types().next().is_none() && projections.peek().is_none() {
589             return;
590         }
591
592         output.push('<');
593
594         for type_parameter in substs.types() {
595             self.push_type_name(type_parameter, output);
596             output.push_str(", ");
597         }
598
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(", ");
606         }
607
608         output.pop();
609         output.pop();
610
611         output.push('>');
612     }
613
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);
619     }
620 }