1 // Copyright 2014 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 //! Translation Item Collection
12 //! ===========================
14 //! This module is responsible for discovering all items that will contribute to
15 //! to code generation of the crate. The important part here is that it not only
16 //! needs to find syntax-level items (functions, structs, etc) but also all
17 //! their monomorphized instantiations. Every non-generic, non-const function
18 //! maps to one LLVM artifact. Every generic function can produce
19 //! from zero to N artifacts, depending on the sets of type arguments it
20 //! is instantiated with.
21 //! This also applies to generic items from other crates: A generic definition
22 //! in crate X might produce monomorphizations that are compiled into crate Y.
23 //! We also have to collect these here.
25 //! The following kinds of "translation items" are handled here:
33 //! The following things also result in LLVM artifacts, but are not collected
34 //! here, since we instantiate them locally on demand when needed in a given
44 //! Let's define some terms first:
46 //! - A "translation item" is something that results in a function or global in
47 //! the LLVM IR of a codegen unit. Translation items do not stand on their
48 //! own, they can reference other translation items. For example, if function
49 //! `foo()` calls function `bar()` then the translation item for `foo()`
50 //! references the translation item for function `bar()`. In general, the
51 //! definition for translation item A referencing a translation item B is that
52 //! the LLVM artifact produced for A references the LLVM artifact produced
55 //! - Translation items and the references between them for a directed graph,
56 //! where the translation items are the nodes and references form the edges.
57 //! Let's call this graph the "translation item graph".
59 //! - The translation item graph for a program contains all translation items
60 //! that are needed in order to produce the complete LLVM IR of the program.
62 //! The purpose of the algorithm implemented in this module is to build the
63 //! translation item graph for the current crate. It runs in two phases:
65 //! 1. Discover the roots of the graph by traversing the HIR of the crate.
66 //! 2. Starting from the roots, find neighboring nodes by inspecting the MIR
67 //! representation of the item corresponding to a given node, until no more
68 //! new nodes are found.
70 //! ### Discovering roots
72 //! The roots of the translation item graph correspond to the non-generic
73 //! syntactic items in the source code. We find them by walking the HIR of the
74 //! crate, and whenever we hit upon a function, method, or static item, we
75 //! create a translation item consisting of the items DefId and, since we only
76 //! consider non-generic items, an empty type-substitution set.
78 //! ### Finding neighbor nodes
79 //! Given a translation item node, we can discover neighbors by inspecting its
80 //! MIR. We walk the MIR and any time we hit upon something that signifies a
81 //! reference to another translation item, we have found a neighbor. Since the
82 //! translation item we are currently at is always monomorphic, we also know the
83 //! concrete type arguments of its neighbors, and so all neighbors again will be
84 //! monomorphic. The specific forms a reference to a neighboring node can take
85 //! in MIR are quite diverse. Here is an overview:
87 //! #### Calling Functions/Methods
88 //! The most obvious form of one translation item referencing another is a
89 //! function or method call (represented by a CALL terminator in MIR). But
90 //! calls are not the only thing that might introduce a reference between two
91 //! function translation items, and as we will see below, they are just a
92 //! specialized of the form described next, and consequently will don't get any
93 //! special treatment in the algorithm.
95 //! #### Taking a reference to a function or method
96 //! A function does not need to actually be called in order to be a neighbor of
97 //! another function. It suffices to just take a reference in order to introduce
98 //! an edge. Consider the following example:
101 //! fn print_val<T: Display>(x: T) {
102 //! println!("{}", x);
105 //! fn call_fn(f: &Fn(i32), x: i32) {
110 //! let print_i32 = print_val::<i32>;
111 //! call_fn(&print_i32, 0);
114 //! The MIR of none of these functions will contain an explicit call to
115 //! `print_val::<i32>`. Nonetheless, in order to translate this program, we need
116 //! an instance of this function. Thus, whenever we encounter a function or
117 //! method in operand position, we treat it as a neighbor of the current
118 //! translation item. Calls are just a special case of that.
121 //! In a way, closures are a simple case. Since every closure object needs to be
122 //! constructed somewhere, we can reliably discover them by observing
123 //! `RValue::Aggregate` expressions with `AggregateKind::Closure`. This is also
124 //! true for closures inlined from other crates.
127 //! Drop glue translation items are introduced by MIR drop-statements. The
128 //! generated translation item will again have drop-glue item neighbors if the
129 //! type to be dropped contains nested values that also need to be dropped. It
130 //! might also have a function item neighbor for the explicit `Drop::drop`
131 //! implementation of its type.
133 //! #### Unsizing Casts
134 //! A subtle way of introducing neighbor edges is by casting to a trait object.
135 //! Since the resulting fat-pointer contains a reference to a vtable, we need to
136 //! instantiate all object-save methods of the trait, as we need to store
137 //! pointers to these functions even if they never get called anywhere. This can
138 //! be seen as a special case of taking a function reference.
141 //! Since `Box` expression have special compiler support, no explicit calls to
142 //! `exchange_malloc()` and `exchange_free()` may show up in MIR, even if the
143 //! compiler will generate them. We have to observe `Rvalue::Box` expressions
144 //! and Box-typed drop-statements for that purpose.
147 //! Interaction with Cross-Crate Inlining
148 //! -------------------------------------
149 //! The binary of a crate will not only contain machine code for the items
150 //! defined in the source code of that crate. It will also contain monomorphic
151 //! instantiations of any extern generic functions and of functions marked with
153 //! The collection algorithm handles this more or less transparently. If it is
154 //! about to create a translation item for something with an external `DefId`,
155 //! it will take a look if the MIR for that item is available, and if so just
156 //! proceed normally. If the MIR is not available, it assumes that that item is
157 //! just linked to and no node is created; which is exactly what we want, since
158 //! no machine code should be generated in the current crate for such an item.
160 //! Eager and Lazy Collection Mode
161 //! ------------------------------
162 //! Translation item collection can be performed in one of two modes:
164 //! - Lazy mode means that items will only be instantiated when actually
165 //! referenced. The goal is to produce the least amount of machine code
168 //! - Eager mode is meant to be used in conjunction with incremental compilation
169 //! where a stable set of translation items is more important than a minimal
170 //! one. Thus, eager mode will instantiate drop-glue for every drop-able type
171 //! in the crate, even of no drop call for that type exists (yet). It will
172 //! also instantiate default implementations of trait methods, something that
173 //! otherwise is only done on demand.
178 //! Some things are not yet fully implemented in the current version of this
181 //! ### Initializers of Constants and Statics
182 //! Since no MIR is constructed yet for initializer expressions of constants and
183 //! statics we cannot inspect these properly.
186 //! Ideally, no translation item should be generated for const fns unless there
187 //! is a call to them that cannot be evaluated at compile time. At the moment
188 //! this is not implemented however: a translation item will be produced
189 //! regardless of whether it is actually needed or not.
191 use rustc_front::hir;
192 use rustc_front::intravisit as hir_visit;
194 use rustc::front::map as hir_map;
195 use rustc::middle::def_id::DefId;
196 use rustc::middle::lang_items::{ExchangeFreeFnLangItem, ExchangeMallocFnLangItem};
197 use rustc::middle::{ty, traits};
198 use rustc::middle::subst::{self, Substs, Subst};
199 use rustc::middle::ty::adjustment::CustomCoerceUnsized;
200 use rustc::middle::ty::fold::TypeFoldable;
201 use rustc::mir::repr as mir;
202 use rustc::mir::visit as mir_visit;
203 use rustc::mir::visit::Visitor as MirVisitor;
205 use syntax::ast::{self, NodeId};
206 use syntax::codemap::DUMMY_SP;
208 use syntax::parse::token;
210 use trans::base::custom_coerce_unsize_info;
211 use trans::context::CrateContext;
212 use trans::common::{fulfill_obligation, normalize_and_test_predicates,
216 use trans::monomorphize;
217 use util::nodemap::{FnvHashSet, FnvHashMap, DefIdMap};
219 use std::hash::{Hash, Hasher};
222 #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
223 pub enum TransItemCollectionMode {
228 #[derive(Eq, Clone, Copy, Debug)]
229 pub enum TransItem<'tcx> {
230 DropGlue(ty::Ty<'tcx>),
233 substs: &'tcx Substs<'tcx>
238 impl<'tcx> Hash for TransItem<'tcx> {
239 fn hash<H: Hasher>(&self, s: &mut H) {
241 TransItem::DropGlue(t) => {
245 TransItem::Fn { def_id, substs } => {
248 (substs as *const Substs<'tcx> as usize).hash(s);
250 TransItem::Static(node_id) => {
258 impl<'tcx> PartialEq for TransItem<'tcx> {
259 fn eq(&self, other: &Self) -> bool {
260 match (*self, *other) {
261 (TransItem::DropGlue(t1), TransItem::DropGlue(t2)) => t1 == t2,
262 (TransItem::Fn { def_id: def_id1, substs: substs1 },
263 TransItem::Fn { def_id: def_id2, substs: substs2 }) => {
264 def_id1 == def_id2 && substs1 == substs2
266 (TransItem::Static(node_id1), TransItem::Static(node_id2)) => {
274 pub fn collect_crate_translation_items<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
275 mode: TransItemCollectionMode)
276 -> FnvHashSet<TransItem<'tcx>> {
277 // We are not tracking dependencies of this pass as it has to be re-executed
278 // every time no matter what.
279 ccx.tcx().dep_graph.with_ignore(|| {
280 let roots = collect_roots(ccx, mode);
282 debug!("Building translation item graph, beginning at roots");
283 let mut visited = FnvHashSet();
284 let mut recursion_depths = DefIdMap();
285 let mut mir_cache = DefIdMap();
288 collect_items_rec(ccx,
291 &mut recursion_depths,
299 // Find all non-generic items by walking the HIR. These items serve as roots to
300 // start monomorphizing from.
301 fn collect_roots<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
302 mode: TransItemCollectionMode)
303 -> Vec<TransItem<'tcx>> {
304 debug!("Collecting roots");
305 let mut roots = Vec::new();
308 let mut visitor = RootCollector {
312 enclosing_item: None,
313 trans_empty_substs: ccx.tcx().mk_substs(Substs::trans_empty()),
316 ccx.tcx().map.krate().visit_all_items(&mut visitor);
323 enum CachedMir<'mir, 'tcx: 'mir> {
324 Ref(&'mir mir::Mir<'tcx>),
325 Owned(Rc<mir::Mir<'tcx>>)
328 impl<'mir, 'tcx: 'mir> CachedMir<'mir, 'tcx> {
329 fn get_ref<'a>(&'a self) -> &'a mir::Mir<'tcx> {
331 CachedMir::Ref(r) => r,
332 CachedMir::Owned(ref rc) => &**rc,
337 // Collect all monomorphized translation items reachable from `starting_point`
338 fn collect_items_rec<'a, 'tcx: 'a>(ccx: &CrateContext<'a, 'tcx>,
339 starting_point: TransItem<'tcx>,
340 visited: &mut FnvHashSet<TransItem<'tcx>>,
341 recursion_depths: &mut DefIdMap<usize>,
342 mir_cache: &mut DefIdMap<CachedMir<'a, 'tcx>>) {
343 if !visited.insert(starting_point.clone()) {
344 // We've been here already, no need to search again.
347 debug!("BEGIN collect_items_rec({})", starting_point.to_string(ccx));
349 let mut neighbors = Vec::new();
350 let recursion_depth_reset;
352 match starting_point {
353 TransItem::DropGlue(_) |
354 TransItem::Static(_) => {
355 recursion_depth_reset = None;
359 substs: ref param_substs
361 // Keep track of the monomorphization recursion depth
362 recursion_depth_reset = Some(check_recursion_limit(ccx,
366 // Scan the MIR in order to find function calls, closures, and
368 let mir = load_mir(ccx, def_id, mir_cache);
370 let mut visitor = MirNeighborCollector {
373 output: &mut neighbors,
374 param_substs: param_substs
377 visitor.visit_mir(mir.get_ref());
381 for neighbour in neighbors {
382 collect_items_rec(ccx, neighbour, visited, recursion_depths, mir_cache);
385 if let Some((def_id, depth)) = recursion_depth_reset {
386 recursion_depths.insert(def_id, depth);
389 debug!("END collect_items_rec({})", starting_point.to_string(ccx));
392 fn load_mir<'a, 'tcx: 'a>(ccx: &CrateContext<'a, 'tcx>,
394 mir_cache: &mut DefIdMap<CachedMir<'a, 'tcx>>)
395 -> CachedMir<'a, 'tcx> {
396 let mir_not_found_error_message = || {
397 format!("Could not find MIR for function: {}",
398 ccx.tcx().item_path_str(def_id))
401 if def_id.is_local() {
402 let node_id = ccx.tcx().map.as_local_node_id(def_id).unwrap();
403 let mir_opt = ccx.mir_map().get(&node_id);
404 let mir = errors::expect(ccx.sess().diagnostic(),
406 mir_not_found_error_message);
409 if let Some(mir) = mir_cache.get(&def_id) {
413 let mir_opt = ccx.sess().cstore.maybe_get_item_mir(ccx.tcx(), def_id);
414 let mir = errors::expect(ccx.sess().diagnostic(),
416 mir_not_found_error_message);
417 let cached = CachedMir::Owned(Rc::new(mir));
418 mir_cache.insert(def_id, cached.clone());
423 fn check_recursion_limit<'a, 'tcx: 'a>(ccx: &CrateContext<'a, 'tcx>,
425 recursion_depths: &mut DefIdMap<usize>)
427 let recursion_depth = recursion_depths.get(&def_id)
430 debug!(" => recursion depth={}", recursion_depth);
432 // Code that needs to instantiate the same function recursively
433 // more than the recursion limit is assumed to be causing an
434 // infinite expansion.
435 if recursion_depth > ccx.sess().recursion_limit.get() {
436 if let Some(node_id) = ccx.tcx().map.as_local_node_id(def_id) {
437 ccx.sess().span_fatal(ccx.tcx().map.span(node_id),
438 "reached the recursion limit during monomorphization");
440 let error = format!("reached the recursion limit during \
441 monomorphization of '{}'",
442 ccx.tcx().item_path_str(def_id));
443 ccx.sess().fatal(&error[..]);
447 recursion_depths.insert(def_id, recursion_depth + 1);
449 (def_id, recursion_depth)
452 struct MirNeighborCollector<'a, 'tcx: 'a> {
453 ccx: &'a CrateContext<'a, 'tcx>,
454 mir: &'a mir::Mir<'tcx>,
455 output: &'a mut Vec<TransItem<'tcx>>,
456 param_substs: &'tcx Substs<'tcx>
459 impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> {
461 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>) {
462 debug!("visiting rvalue {:?}", *rvalue);
465 mir::Rvalue::Aggregate(mir::AggregateKind::Closure(def_id,
467 assert!(can_have_local_instance(self.ccx, def_id));
468 let trans_item = create_fn_trans_item(self.ccx,
472 self.output.push(trans_item);
474 // When doing an cast from a regular pointer to a fat pointer, we
475 // have to instantiate all methods of the trait being cast to, so we
476 // can build the appropriate vtable.
477 mir::Rvalue::Cast(mir::CastKind::Unsize, ref operand, target_ty) => {
478 let target_ty = monomorphize::apply_param_substs(self.ccx.tcx(),
481 let source_ty = self.mir.operand_ty(self.ccx.tcx(), operand);
482 let source_ty = monomorphize::apply_param_substs(self.ccx.tcx(),
485 let (source_ty, target_ty) = find_vtable_types_for_unsizing(self.ccx,
488 // This could also be a different Unsize instruction, like
489 // from a fixed sized array to a slice. But we are only
490 // interested in things that produce a vtable.
491 if target_ty.is_trait() && !source_ty.is_trait() {
492 create_trans_items_for_vtable_methods(self.ccx,
498 mir::Rvalue::Box(_) => {
499 let exchange_malloc_fn_def_id =
503 .require(ExchangeMallocFnLangItem)
504 .expect("Could not find ExchangeMallocFnLangItem");
506 assert!(can_have_local_instance(self.ccx, exchange_malloc_fn_def_id));
507 let exchange_malloc_fn_trans_item =
508 create_fn_trans_item(self.ccx,
509 exchange_malloc_fn_def_id,
510 &Substs::trans_empty(),
513 self.output.push(exchange_malloc_fn_trans_item);
515 _ => { /* not interesting */ }
518 self.super_rvalue(rvalue);
521 fn visit_lvalue(&mut self,
522 lvalue: &mir::Lvalue<'tcx>,
523 context: mir_visit::LvalueContext) {
524 debug!("visiting lvalue {:?}", *lvalue);
526 if let mir_visit::LvalueContext::Drop = context {
527 let ty = self.mir.lvalue_ty(self.ccx.tcx(), lvalue)
528 .to_ty(self.ccx.tcx());
530 let ty = monomorphize::apply_param_substs(self.ccx.tcx(),
533 let ty = self.ccx.tcx().erase_regions(&ty);
535 create_drop_glue_trans_items(self.ccx,
541 self.super_lvalue(lvalue, context);
544 fn visit_operand(&mut self, operand: &mir::Operand<'tcx>) {
545 debug!("visiting operand {:?}", *operand);
547 let callee = match *operand {
548 mir::Operand::Constant(mir::Constant {
549 literal: mir::Literal::Item {
555 }) if is_function_or_method(kind) => Some((def_id, substs)),
559 if let Some((callee_def_id, callee_substs)) = callee {
560 debug!(" => operand is callable");
562 // `callee_def_id` might refer to a trait method instead of a
563 // concrete implementation, so we have to find the actual
564 // implementation. For example, the call might look like
566 // std::cmp::partial_cmp(0i32, 1i32)
568 // Calling do_static_dispatch() here will map the def_id of
569 // `std::cmp::partial_cmp` to the def_id of `i32::partial_cmp<i32>`
570 let dispatched = do_static_dispatch(self.ccx,
575 if let Some((callee_def_id, callee_substs)) = dispatched {
576 // if we have a concrete impl (which we might not have
577 // in the case of something compiler generated like an
578 // object shim or a closure that is handled differently),
579 // we check if the callee is something that will actually
580 // result in a translation item ...
581 if can_result_in_trans_item(self.ccx, callee_def_id) {
582 // ... and create one if it does.
583 let trans_item = create_fn_trans_item(self.ccx,
587 self.output.push(trans_item);
592 self.super_operand(operand);
594 fn is_function_or_method(item_kind: mir::ItemKind) -> bool {
596 mir::ItemKind::Constant => false,
597 mir::ItemKind::Function |
598 mir::ItemKind::Method => true
602 fn can_result_in_trans_item<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
605 if !match ccx.tcx().lookup_item_type(def_id).ty.sty {
606 ty::TyBareFn(Some(def_id), _) => {
607 // Some constructors also have type TyBareFn but they are
608 // always instantiated inline and don't result in
610 match ccx.tcx().map.get_if_local(def_id) {
611 Some(hir_map::NodeVariant(_)) |
612 Some(hir_map::NodeStructCtor(_)) => false,
615 ccx.sess().cstore.variant_kind(def_id).is_none()
619 ty::TyClosure(..) => true,
625 can_have_local_instance(ccx, def_id)
630 fn can_have_local_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
633 // Take a look if we have the definition available. If not, we
634 // will not emit code for this item in the local crate, and thus
635 // don't create a translation item for it.
636 def_id.is_local() || ccx.sess().cstore.is_item_mir_available(def_id)
639 fn create_drop_glue_trans_items<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
640 mono_ty: ty::Ty<'tcx>,
641 param_substs: &'tcx Substs<'tcx>,
642 output: &mut Vec<TransItem<'tcx>>)
644 visit_types_of_owned_components(ccx,
648 debug!("create_drop_glue_trans_items: {}", type_to_string(ccx, ty));
649 // Add a translation item for the drop glue, if even this type does not
650 // need to be dropped (in which case it has been mapped to i8)
651 output.push(TransItem::DropGlue(ty));
653 if glue::type_needs_drop(ccx.tcx(), ty) {
655 // Make sure the exchange_free_fn() lang-item gets translated if
656 // there is a boxed value.
657 if let ty::TyBox(_) = ty.sty {
659 let exchange_free_fn_def_id = ccx.tcx()
661 .require(ExchangeFreeFnLangItem)
662 .expect("Could not find ExchangeFreeFnLangItem");
664 assert!(can_have_local_instance(ccx, exchange_free_fn_def_id));
665 let exchange_free_fn_trans_item =
666 create_fn_trans_item(ccx,
667 exchange_free_fn_def_id,
668 &Substs::trans_empty(),
671 output.push(exchange_free_fn_trans_item);
674 // If the type implements Drop, also add a translation item for the
675 // monomorphized Drop::drop() implementation.
676 let destructor_did = match ty.sty {
677 ty::TyStruct(def, _) |
678 ty::TyEnum(def, _) => def.destructor(),
682 if let Some(destructor_did) = destructor_did {
683 use rustc::middle::ty::ToPolyTraitRef;
685 let drop_trait_def_id = ccx.tcx()
690 let self_type_substs = ccx.tcx().mk_substs(
691 Substs::trans_empty().with_self_ty(ty));
693 let trait_ref = ty::TraitRef {
694 def_id: drop_trait_def_id,
695 substs: self_type_substs,
696 }.to_poly_trait_ref();
698 let substs = match fulfill_obligation(ccx, DUMMY_SP, trait_ref) {
699 traits::VtableImpl(data) => data.substs,
703 if can_have_local_instance(ccx, destructor_did) {
704 let trans_item = create_fn_trans_item(ccx,
706 ccx.tcx().mk_substs(substs),
708 output.push(trans_item);
718 fn visit_types_of_owned_components<'a, 'tcx, F>(ccx: &CrateContext<'a, 'tcx>,
720 visited: &mut FnvHashSet<ty::Ty<'tcx>>,
722 where F: FnMut(ty::Ty<'tcx>) -> bool
724 let ty = glue::get_drop_glue_type(ccx, ty);
726 if !visited.insert(ty) {
731 // Don't recurse further
749 ty::TyStruct(ref adt_def, substs) |
750 ty::TyEnum(ref adt_def, substs) => {
751 for field in adt_def.all_fields() {
752 let field_type = monomorphize::apply_param_substs(ccx.tcx(),
754 &field.unsubst_ty());
755 visit_types_of_owned_components(ccx, field_type, visited, f);
758 ty::TyClosure(_, ref substs) => {
759 for upvar_ty in &substs.upvar_tys {
760 visit_types_of_owned_components(ccx, upvar_ty, visited, f);
763 ty::TyBox(inner_type) |
764 ty::TyArray(inner_type, _) => {
765 visit_types_of_owned_components(ccx, inner_type, visited, f);
767 ty::TyTuple(ref args) => {
769 visit_types_of_owned_components(ccx, arg, visited, f);
772 ty::TyProjection(_) |
776 ccx.sess().bug("encountered unexpected type");
782 fn do_static_dispatch<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
784 fn_substs: &'tcx Substs<'tcx>,
785 param_substs: &'tcx Substs<'tcx>)
786 -> Option<(DefId, &'tcx Substs<'tcx>)> {
787 debug!("do_static_dispatch(fn_def_id={}, fn_substs={:?}, param_substs={:?})",
788 def_id_to_string(ccx, fn_def_id, None),
792 let is_trait_method = ccx.tcx().trait_of_item(fn_def_id).is_some();
795 match ccx.tcx().impl_or_trait_item(fn_def_id) {
796 ty::MethodTraitItem(ref method) => {
797 match method.container {
798 ty::TraitContainer(trait_def_id) => {
799 debug!(" => trait method, attempting to find impl");
800 do_static_trait_method_dispatch(ccx,
806 ty::ImplContainer(_) => {
807 // This is already a concrete implementation
808 debug!(" => impl method");
809 Some((fn_def_id, fn_substs))
816 debug!(" => regular function");
817 // The function is not part of an impl or trait, no dispatching
819 Some((fn_def_id, fn_substs))
823 // Given a trait-method and substitution information, find out the actual
824 // implementation of the trait method.
825 fn do_static_trait_method_dispatch<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
826 trait_method: &ty::Method,
828 callee_substs: &'tcx Substs<'tcx>,
829 param_substs: &'tcx Substs<'tcx>)
830 -> Option<(DefId, &'tcx Substs<'tcx>)> {
832 debug!("do_static_trait_method_dispatch(trait_method={}, \
834 callee_substs={:?}, \
836 def_id_to_string(ccx, trait_method.def_id, None),
837 def_id_to_string(ccx, trait_id, None),
841 let rcvr_substs = monomorphize::apply_param_substs(tcx,
845 let trait_ref = ty::Binder(rcvr_substs.to_trait_ref(tcx, trait_id));
846 let vtbl = fulfill_obligation(ccx, DUMMY_SP, trait_ref);
848 // Now that we know which impl is being used, we can dispatch to
849 // the actual function:
851 traits::VtableImpl(traits::VtableImplData {
852 impl_def_id: impl_did,
856 let callee_substs = impl_substs.with_method_from(&rcvr_substs);
857 let impl_method = tcx.get_impl_method(impl_did,
860 Some((impl_method.method.def_id, tcx.mk_substs(impl_method.substs)))
862 // If we have a closure or a function pointer, we will also encounter
863 // the concrete closure/function somewhere else (during closure or fn
864 // pointer construction). That's where we track those things.
865 traits::VtableClosure(..) |
866 traits::VtableFnPointer(..) |
867 traits::VtableObject(..) => {
871 tcx.sess.bug(&format!("static call to invalid vtable: {:?}", vtbl))
876 /// For given pair of source and target type that occur in an unsizing coercion,
877 /// this function finds the pair of types that determines the vtable linking
880 /// For example, the source type might be `&SomeStruct` and the target type\
881 /// might be `&SomeTrait` in a cast like:
883 /// let src: &SomeStruct = ...;
884 /// let target = src as &SomeTrait;
886 /// Then the output of this function would be (SomeStruct, SomeTrait) since for
887 /// constructing the `target` fat-pointer we need the vtable for that pair.
889 /// Things can get more complicated though because there's also the case where
890 /// the unsized type occurs as a field:
893 /// struct ComplexStruct<T: ?Sized> {
900 /// In this case, if `T` is sized, `&ComplexStruct<T>` is a thin pointer. If `T`
901 /// is unsized, `&SomeStruct` is a fat pointer, and the vtable it points to is
902 /// for the pair of `T` (which is a trait) and the concrete type that `T` was
903 /// originally coerced from:
905 /// let src: &ComplexStruct<SomeStruct> = ...;
906 /// let target = src as &ComplexStruct<SomeTrait>;
908 /// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
909 /// `(SomeStruct, SomeTrait)`.
911 /// Finally, there is also the case of custom unsizing coercions, e.g. for
912 /// smart pointers such as `Rc` and `Arc`.
913 fn find_vtable_types_for_unsizing<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
914 source_ty: ty::Ty<'tcx>,
915 target_ty: ty::Ty<'tcx>)
916 -> (ty::Ty<'tcx>, ty::Ty<'tcx>) {
917 match (&source_ty.sty, &target_ty.sty) {
918 (&ty::TyBox(a), &ty::TyBox(b)) |
919 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
920 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
921 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
922 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
923 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
924 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
925 let (inner_source, inner_target) = (a, b);
927 if !type_is_sized(ccx.tcx(), inner_source) {
928 (inner_source, inner_target)
930 ccx.tcx().struct_lockstep_tails(inner_source, inner_target)
934 (&ty::TyStruct(source_adt_def, source_substs),
935 &ty::TyStruct(target_adt_def, target_substs)) => {
936 assert_eq!(source_adt_def, target_adt_def);
938 let kind = custom_coerce_unsize_info(ccx, source_ty, target_ty);
940 let coerce_index = match kind {
941 CustomCoerceUnsized::Struct(i) => i
944 let source_fields = &source_adt_def.struct_variant().fields;
945 let target_fields = &target_adt_def.struct_variant().fields;
947 assert!(coerce_index < source_fields.len() &&
948 source_fields.len() == target_fields.len());
950 find_vtable_types_for_unsizing(ccx,
951 source_fields[coerce_index].ty(ccx.tcx(),
953 target_fields[coerce_index].ty(ccx.tcx(),
957 .bug(&format!("find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
963 fn create_fn_trans_item<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
965 fn_substs: &Substs<'tcx>,
966 param_substs: &Substs<'tcx>)
969 debug!("create_fn_trans_item(def_id={}, fn_substs={:?}, param_substs={:?})",
970 def_id_to_string(ccx, def_id, None),
974 // We only get here, if fn_def_id either designates a local item or
975 // an inlineable external item. Non-inlineable external items are
976 // ignored because we don't want to generate any code for them.
977 let concrete_substs = monomorphize::apply_param_substs(ccx.tcx(),
980 let concrete_substs = ccx.tcx().erase_regions(&concrete_substs);
982 let trans_item = TransItem::Fn {
984 substs: ccx.tcx().mk_substs(concrete_substs),
990 /// Creates a `TransItem` for each method that is referenced by the vtable for
991 /// the given trait/impl pair.
992 fn create_trans_items_for_vtable_methods<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
993 trait_ty: ty::Ty<'tcx>,
994 impl_ty: ty::Ty<'tcx>,
995 output: &mut Vec<TransItem<'tcx>>) {
996 assert!(!trait_ty.needs_subst() && !impl_ty.needs_subst());
998 if let ty::TyTrait(ref trait_ty) = trait_ty.sty {
999 let poly_trait_ref = trait_ty.principal_trait_ref_with_self_ty(ccx.tcx(),
1002 // Walk all methods of the trait, including those of its supertraits
1003 for trait_ref in traits::supertraits(ccx.tcx(), poly_trait_ref) {
1004 let vtable = fulfill_obligation(ccx, DUMMY_SP, trait_ref);
1007 traits::VtableImplData {
1011 let items = meth::get_vtable_methods(ccx, impl_def_id, substs)
1013 // filter out None values
1014 .filter_map(|opt_impl_method| opt_impl_method)
1015 // create translation items
1016 .filter_map(|impl_method| {
1017 if can_have_local_instance(ccx, impl_method.method.def_id) {
1018 let substs = ccx.tcx().mk_substs(impl_method.substs);
1019 Some(create_fn_trans_item(ccx,
1020 impl_method.method.def_id,
1022 &Substs::trans_empty()))
1027 .collect::<Vec<_>>();
1029 output.extend(items.into_iter());
1037 //=-----------------------------------------------------------------------------
1039 //=-----------------------------------------------------------------------------
1041 struct RootCollector<'b, 'a: 'b, 'tcx: 'a + 'b> {
1042 ccx: &'b CrateContext<'a, 'tcx>,
1043 mode: TransItemCollectionMode,
1044 output: &'b mut Vec<TransItem<'tcx>>,
1045 enclosing_item: Option<&'tcx hir::Item>,
1046 trans_empty_substs: &'tcx Substs<'tcx>
1049 impl<'b, 'a, 'v> hir_visit::Visitor<'v> for RootCollector<'b, 'a, 'v> {
1050 fn visit_item(&mut self, item: &'v hir::Item) {
1051 let old_enclosing_item = self.enclosing_item;
1052 self.enclosing_item = Some(item);
1055 hir::ItemExternCrate(..) |
1057 hir::ItemForeignMod(..) |
1059 hir::ItemDefaultImpl(..) |
1060 hir::ItemTrait(..) |
1061 hir::ItemConst(..) |
1062 hir::ItemMod(..) => {
1063 // Nothing to do, just keep recursing...
1066 hir::ItemImpl(..) => {
1067 if self.mode == TransItemCollectionMode::Eager {
1068 create_trans_items_for_default_impls(self.ccx,
1070 self.trans_empty_substs,
1075 hir::ItemEnum(_, ref generics) |
1076 hir::ItemStruct(_, ref generics) => {
1077 if !generics.is_parameterized() {
1079 let tables = self.ccx.tcx().tables.borrow();
1080 tables.node_types[&item.id]
1083 if self.mode == TransItemCollectionMode::Eager {
1084 debug!("RootCollector: ADT drop-glue for {}",
1085 def_id_to_string(self.ccx,
1086 self.ccx.tcx().map.local_def_id(item.id),
1089 create_drop_glue_trans_items(self.ccx,
1091 self.trans_empty_substs,
1096 hir::ItemStatic(..) => {
1097 debug!("RootCollector: ItemStatic({})",
1098 def_id_to_string(self.ccx,
1099 self.ccx.tcx().map.local_def_id(item.id),
1101 self.output.push(TransItem::Static(item.id));
1103 hir::ItemFn(_, _, constness, _, ref generics, _) => {
1104 if !generics.is_type_parameterized() &&
1105 constness == hir::Constness::NotConst {
1106 let def_id = self.ccx.tcx().map.local_def_id(item.id);
1108 debug!("RootCollector: ItemFn({})",
1109 def_id_to_string(self.ccx, def_id, None));
1111 self.output.push(TransItem::Fn {
1113 substs: self.trans_empty_substs
1119 hir_visit::walk_item(self, item);
1120 self.enclosing_item = old_enclosing_item;
1123 fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
1125 hir::ImplItemKind::Method(hir::MethodSig {
1129 }, _) if constness == hir::Constness::NotConst => {
1130 let hir_map = &self.ccx.tcx().map;
1131 let parent_node_id = hir_map.get_parent_node(ii.id);
1132 let is_impl_generic = match hir_map.expect_item(parent_node_id) {
1134 node: hir::ItemImpl(_, _, ref generics, _, _, _),
1137 generics.is_type_parameterized()
1144 if !generics.is_type_parameterized() && !is_impl_generic {
1145 let def_id = self.ccx.tcx().map.local_def_id(ii.id);
1147 debug!("RootCollector: MethodImplItem({})",
1148 def_id_to_string(self.ccx, def_id, None));
1150 self.output.push(TransItem::Fn {
1152 substs: self.trans_empty_substs
1156 _ => { /* Nothing to do here */ }
1159 hir_visit::walk_impl_item(self, ii)
1163 fn create_trans_items_for_default_impls<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1164 item: &'tcx hir::Item,
1165 trans_empty_substs: &'tcx Substs<'tcx>,
1166 output: &mut Vec<TransItem<'tcx>>) {
1174 if generics.is_type_parameterized() {
1178 let tcx = ccx.tcx();
1179 let impl_def_id = tcx.map.local_def_id(item.id);
1181 debug!("create_trans_items_for_default_impls(item={})",
1182 def_id_to_string(ccx, impl_def_id, None));
1184 if let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1185 let default_impls = tcx.provided_trait_methods(trait_ref.def_id);
1186 let callee_substs = tcx.mk_substs(tcx.erase_regions(trait_ref.substs));
1187 let overridden_methods: FnvHashSet<_> = items.iter()
1188 .map(|item| item.name)
1190 for default_impl in default_impls {
1191 if overridden_methods.contains(&default_impl.name) {
1195 if default_impl.generics.has_type_params(subst::FnSpace) {
1199 // The substitutions we have are on the impl, so we grab
1200 // the method type from the impl to substitute into.
1201 let mth = tcx.get_impl_method(impl_def_id,
1202 callee_substs.clone(),
1205 assert!(mth.is_provided);
1207 let predicates = mth.method.predicates.predicates.subst(tcx, &mth.substs);
1208 if !normalize_and_test_predicates(ccx, predicates.into_vec()) {
1212 if can_have_local_instance(ccx, default_impl.def_id) {
1213 let item = create_fn_trans_item(ccx,
1214 default_impl.def_id,
1216 trans_empty_substs);
1228 //=-----------------------------------------------------------------------------
1229 // TransItem String Keys
1230 //=-----------------------------------------------------------------------------
1232 // The code below allows for producing a unique string key for a trans item.
1233 // These keys are used by the handwritten auto-tests, so they need to be
1234 // predictable and human-readable.
1236 // Note: A lot of this could looks very similar to what's already in the
1237 // ppaux module. It would be good to refactor things so we only have one
1238 // parameterizable implementation for printing types.
1240 /// Same as `unique_type_name()` but with the result pushed onto the given
1241 /// `output` parameter.
1242 pub fn push_unique_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1244 output: &mut String) {
1246 ty::TyBool => output.push_str("bool"),
1247 ty::TyChar => output.push_str("char"),
1248 ty::TyStr => output.push_str("str"),
1249 ty::TyInt(ast::TyIs) => output.push_str("isize"),
1250 ty::TyInt(ast::TyI8) => output.push_str("i8"),
1251 ty::TyInt(ast::TyI16) => output.push_str("i16"),
1252 ty::TyInt(ast::TyI32) => output.push_str("i32"),
1253 ty::TyInt(ast::TyI64) => output.push_str("i64"),
1254 ty::TyUint(ast::TyUs) => output.push_str("usize"),
1255 ty::TyUint(ast::TyU8) => output.push_str("u8"),
1256 ty::TyUint(ast::TyU16) => output.push_str("u16"),
1257 ty::TyUint(ast::TyU32) => output.push_str("u32"),
1258 ty::TyUint(ast::TyU64) => output.push_str("u64"),
1259 ty::TyFloat(ast::TyF32) => output.push_str("f32"),
1260 ty::TyFloat(ast::TyF64) => output.push_str("f64"),
1261 ty::TyStruct(adt_def, substs) |
1262 ty::TyEnum(adt_def, substs) => {
1263 push_item_name(cx, adt_def.did, output);
1264 push_type_params(cx, substs, &[], output);
1266 ty::TyTuple(ref component_types) => {
1268 for &component_type in component_types {
1269 push_unique_type_name(cx, component_type, output);
1270 output.push_str(", ");
1272 if !component_types.is_empty() {
1278 ty::TyBox(inner_type) => {
1279 output.push_str("Box<");
1280 push_unique_type_name(cx, inner_type, output);
1283 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
1286 hir::MutImmutable => output.push_str("const "),
1287 hir::MutMutable => output.push_str("mut "),
1290 push_unique_type_name(cx, inner_type, output);
1292 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
1294 if mutbl == hir::MutMutable {
1295 output.push_str("mut ");
1298 push_unique_type_name(cx, inner_type, output);
1300 ty::TyArray(inner_type, len) => {
1302 push_unique_type_name(cx, inner_type, output);
1303 output.push_str(&format!("; {}", len));
1306 ty::TySlice(inner_type) => {
1308 push_unique_type_name(cx, inner_type, output);
1311 ty::TyTrait(ref trait_data) => {
1312 push_item_name(cx, trait_data.principal.skip_binder().def_id, output);
1313 push_type_params(cx,
1314 &trait_data.principal.skip_binder().substs,
1315 &trait_data.bounds.projection_bounds,
1318 ty::TyBareFn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => {
1319 if unsafety == hir::Unsafety::Unsafe {
1320 output.push_str("unsafe ");
1323 if abi != ::syntax::abi::Rust {
1324 output.push_str("extern \"");
1325 output.push_str(abi.name());
1326 output.push_str("\" ");
1329 output.push_str("fn(");
1331 let sig = cx.tcx().erase_late_bound_regions(sig);
1332 if !sig.inputs.is_empty() {
1333 for ¶meter_type in &sig.inputs {
1334 push_unique_type_name(cx, parameter_type, output);
1335 output.push_str(", ");
1342 if !sig.inputs.is_empty() {
1343 output.push_str(", ...");
1345 output.push_str("...");
1352 ty::FnConverging(result_type) if result_type.is_nil() => {}
1353 ty::FnConverging(result_type) => {
1354 output.push_str(" -> ");
1355 push_unique_type_name(cx, result_type, output);
1357 ty::FnDiverging => {
1358 output.push_str(" -> !");
1362 ty::TyClosure(def_id, ref closure_substs) => {
1363 push_item_name(cx, def_id, output);
1364 output.push_str("{");
1365 output.push_str(&format!("{}:{}", def_id.krate, def_id.index.as_usize()));
1366 output.push_str("}");
1367 push_type_params(cx, closure_substs.func_substs, &[], output);
1371 ty::TyProjection(..) |
1373 cx.sess().bug(&format!("debuginfo: Trying to create type name for \
1374 unexpected type: {:?}", t));
1379 fn push_item_name(ccx: &CrateContext,
1381 output: &mut String) {
1382 if def_id.is_local() {
1383 let node_id = ccx.tcx().map.as_local_node_id(def_id).unwrap();
1384 let inlined_from = ccx.external_srcs()
1387 .map(|def_id| *def_id);
1389 if let Some(extern_def_id) = inlined_from {
1390 push_item_name(ccx, extern_def_id, output);
1394 output.push_str(&ccx.link_meta().crate_name);
1395 output.push_str("::");
1398 for part in ccx.tcx().def_path(def_id) {
1399 output.push_str(&format!("{}[{}]::",
1400 part.data.as_interned_str(),
1401 part.disambiguator));
1408 fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1409 substs: &Substs<'tcx>,
1410 projections: &[ty::PolyProjectionPredicate<'tcx>],
1411 output: &mut String) {
1412 if substs.types.is_empty() && projections.is_empty() {
1418 for &type_parameter in &substs.types {
1419 push_unique_type_name(cx, type_parameter, output);
1420 output.push_str(", ");
1423 for projection in projections {
1424 let projection = projection.skip_binder();
1425 let name = token::get_ident_interner().get(projection.projection_ty.item_name);
1426 output.push_str(&name[..]);
1427 output.push_str("=");
1428 push_unique_type_name(cx, projection.ty, output);
1429 output.push_str(", ");
1438 fn push_def_id_as_string<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1440 substs: Option<&Substs<'tcx>>,
1441 output: &mut String) {
1442 push_item_name(ccx, def_id, output);
1444 if let Some(substs) = substs {
1445 push_type_params(ccx, substs, &[], output);
1449 fn def_id_to_string<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1451 substs: Option<&Substs<'tcx>>)
1453 let mut output = String::new();
1454 push_def_id_as_string(ccx, def_id, substs, &mut output);
1458 fn type_to_string<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1461 let mut output = String::new();
1462 push_unique_type_name(ccx, ty, &mut output);
1466 impl<'tcx> TransItem<'tcx> {
1468 pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String {
1469 let hir_map = &ccx.tcx().map;
1471 return match *self {
1472 TransItem::DropGlue(t) => {
1473 let mut s = String::with_capacity(32);
1474 s.push_str("drop-glue ");
1475 push_unique_type_name(ccx, t, &mut s);
1478 TransItem::Fn { def_id, ref substs } => {
1479 to_string_internal(ccx, "fn ", def_id, Some(substs))
1481 TransItem::Static(node_id) => {
1482 let def_id = hir_map.local_def_id(node_id);
1483 to_string_internal(ccx, "static ", def_id, None)
1487 fn to_string_internal<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1490 substs: Option<&Substs<'tcx>>)
1492 let mut result = String::with_capacity(32);
1493 result.push_str(prefix);
1494 push_def_id_as_string(ccx, def_id, substs, &mut result);
1499 fn to_raw_string(&self) -> String {
1501 TransItem::DropGlue(t) => {
1502 format!("DropGlue({})", t as *const _ as usize)
1504 TransItem::Fn { def_id, substs } => {
1505 format!("Fn({:?}, {})",
1507 substs as *const _ as usize)
1509 TransItem::Static(id) => {
1510 format!("Static({:?})", id)
1516 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1517 pub enum TransItemState {
1518 PredictedAndGenerated,
1519 PredictedButNotGenerated,
1520 NotPredictedButGenerated,
1523 pub fn collecting_debug_information(ccx: &CrateContext) -> bool {
1524 return cfg!(debug_assertions) &&
1525 ccx.sess().opts.debugging_opts.print_trans_items.is_some();
1528 pub fn print_collection_results<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>) {
1529 use std::hash::{Hash, SipHasher, Hasher};
1531 if !collecting_debug_information(ccx) {
1535 fn hash<T: Hash>(t: &T) -> u64 {
1536 let mut s = SipHasher::new();
1541 let trans_items = ccx.translation_items().borrow();
1544 // Check for duplicate item keys
1545 let mut item_keys = FnvHashMap();
1547 for (item, item_state) in trans_items.iter() {
1548 let k = item.to_string(&ccx);
1550 if item_keys.contains_key(&k) {
1551 let prev: (TransItem, TransItemState) = item_keys[&k];
1552 debug!("DUPLICATE KEY: {}", k);
1553 debug!(" (1) {:?}, {:?}, hash: {}, raw: {}",
1557 prev.0.to_raw_string());
1559 debug!(" (2) {:?}, {:?}, hash: {}, raw: {}",
1563 item.to_raw_string());
1565 item_keys.insert(k, (*item, *item_state));
1570 let mut predicted_but_not_generated = FnvHashSet();
1571 let mut not_predicted_but_generated = FnvHashSet();
1572 let mut predicted = FnvHashSet();
1573 let mut generated = FnvHashSet();
1575 for (item, item_state) in trans_items.iter() {
1576 let item_key = item.to_string(&ccx);
1579 TransItemState::PredictedAndGenerated => {
1580 predicted.insert(item_key.clone());
1581 generated.insert(item_key);
1583 TransItemState::PredictedButNotGenerated => {
1584 predicted_but_not_generated.insert(item_key.clone());
1585 predicted.insert(item_key);
1587 TransItemState::NotPredictedButGenerated => {
1588 not_predicted_but_generated.insert(item_key.clone());
1589 generated.insert(item_key);
1594 debug!("Total number of translation items predicted: {}", predicted.len());
1595 debug!("Total number of translation items generated: {}", generated.len());
1596 debug!("Total number of translation items predicted but not generated: {}",
1597 predicted_but_not_generated.len());
1598 debug!("Total number of translation items not predicted but generated: {}",
1599 not_predicted_but_generated.len());
1601 if generated.len() > 0 {
1602 debug!("Failed to predict {}% of translation items",
1603 (100 * not_predicted_but_generated.len()) / generated.len());
1605 if generated.len() > 0 {
1606 debug!("Predict {}% too many translation items",
1607 (100 * predicted_but_not_generated.len()) / generated.len());
1611 debug!("Not predicted but generated:");
1612 debug!("============================");
1613 for item in not_predicted_but_generated {
1614 debug!(" - {}", item);
1618 debug!("Predicted but not generated:");
1619 debug!("============================");
1620 for item in predicted_but_not_generated {
1621 debug!(" - {}", item);