]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/partitioning.rs
Merge branch 'refactor-select' of https://github.com/aravind-pg/rust into update...
[rust.git] / src / librustc_mir / monomorphize / partitioning.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 //! Partitioning Codegen Units for Incremental Compilation
12 //! ======================================================
13 //!
14 //! The task of this module is to take the complete set of translation items of
15 //! a crate and produce a set of codegen units from it, where a codegen unit
16 //! is a named set of (translation-item, linkage) pairs. That is, this module
17 //! decides which translation item appears in which codegen units with which
18 //! linkage. The following paragraphs describe some of the background on the
19 //! partitioning scheme.
20 //!
21 //! The most important opportunity for saving on compilation time with
22 //! incremental compilation is to avoid re-translating and re-optimizing code.
23 //! Since the unit of translation and optimization for LLVM is "modules" or, how
24 //! we call them "codegen units", the particulars of how much time can be saved
25 //! by incremental compilation are tightly linked to how the output program is
26 //! partitioned into these codegen units prior to passing it to LLVM --
27 //! especially because we have to treat codegen units as opaque entities once
28 //! they are created: There is no way for us to incrementally update an existing
29 //! LLVM module and so we have to build any such module from scratch if it was
30 //! affected by some change in the source code.
31 //!
32 //! From that point of view it would make sense to maximize the number of
33 //! codegen units by, for example, putting each function into its own module.
34 //! That way only those modules would have to be re-compiled that were actually
35 //! affected by some change, minimizing the number of functions that could have
36 //! been re-used but just happened to be located in a module that is
37 //! re-compiled.
38 //!
39 //! However, since LLVM optimization does not work across module boundaries,
40 //! using such a highly granular partitioning would lead to very slow runtime
41 //! code since it would effectively prohibit inlining and other inter-procedure
42 //! optimizations. We want to avoid that as much as possible.
43 //!
44 //! Thus we end up with a trade-off: The bigger the codegen units, the better
45 //! LLVM's optimizer can do its work, but also the smaller the compilation time
46 //! reduction we get from incremental compilation.
47 //!
48 //! Ideally, we would create a partitioning such that there are few big codegen
49 //! units with few interdependencies between them. For now though, we use the
50 //! following heuristic to determine the partitioning:
51 //!
52 //! - There are two codegen units for every source-level module:
53 //! - One for "stable", that is non-generic, code
54 //! - One for more "volatile" code, i.e. monomorphized instances of functions
55 //!   defined in that module
56 //!
57 //! In order to see why this heuristic makes sense, let's take a look at when a
58 //! codegen unit can get invalidated:
59 //!
60 //! 1. The most straightforward case is when the BODY of a function or global
61 //! changes. Then any codegen unit containing the code for that item has to be
62 //! re-compiled. Note that this includes all codegen units where the function
63 //! has been inlined.
64 //!
65 //! 2. The next case is when the SIGNATURE of a function or global changes. In
66 //! this case, all codegen units containing a REFERENCE to that item have to be
67 //! re-compiled. This is a superset of case 1.
68 //!
69 //! 3. The final and most subtle case is when a REFERENCE to a generic function
70 //! is added or removed somewhere. Even though the definition of the function
71 //! might be unchanged, a new REFERENCE might introduce a new monomorphized
72 //! instance of this function which has to be placed and compiled somewhere.
73 //! Conversely, when removing a REFERENCE, it might have been the last one with
74 //! that particular set of generic arguments and thus we have to remove it.
75 //!
76 //! From the above we see that just using one codegen unit per source-level
77 //! module is not such a good idea, since just adding a REFERENCE to some
78 //! generic item somewhere else would invalidate everything within the module
79 //! containing the generic item. The heuristic above reduces this detrimental
80 //! side-effect of references a little by at least not touching the non-generic
81 //! code of the module.
82 //!
83 //! A Note on Inlining
84 //! ------------------
85 //! As briefly mentioned above, in order for LLVM to be able to inline a
86 //! function call, the body of the function has to be available in the LLVM
87 //! module where the call is made. This has a few consequences for partitioning:
88 //!
89 //! - The partitioning algorithm has to take care of placing functions into all
90 //!   codegen units where they should be available for inlining. It also has to
91 //!   decide on the correct linkage for these functions.
92 //!
93 //! - The partitioning algorithm has to know which functions are likely to get
94 //!   inlined, so it can distribute function instantiations accordingly. Since
95 //!   there is no way of knowing for sure which functions LLVM will decide to
96 //!   inline in the end, we apply a heuristic here: Only functions marked with
97 //!   `#[inline]` are considered for inlining by the partitioner. The current
98 //!   implementation will not try to determine if a function is likely to be
99 //!   inlined by looking at the functions definition.
100 //!
101 //! Note though that as a side-effect of creating a codegen units per
102 //! source-level module, functions from the same module will be available for
103 //! inlining, even when they are not marked #[inline].
104
105 use monomorphize::collector::InliningMap;
106 use rustc::dep_graph::WorkProductId;
107 use rustc::hir::def_id::DefId;
108 use rustc::hir::map::DefPathData;
109 use rustc::mir::mono::{Linkage, Visibility};
110 use rustc::middle::exported_symbols::SymbolExportLevel;
111 use rustc::ty::{self, TyCtxt, InstanceDef};
112 use rustc::ty::item_path::characteristic_def_id_of_type;
113 use rustc::util::nodemap::{FxHashMap, FxHashSet};
114 use std::collections::hash_map::Entry;
115 use syntax::ast::NodeId;
116 use syntax::symbol::{Symbol, InternedString};
117 use rustc::mir::mono::MonoItem;
118 use monomorphize::item::{MonoItemExt, InstantiationMode};
119 use core::usize;
120
121 pub use rustc::mir::mono::CodegenUnit;
122
123 pub enum PartitioningStrategy {
124     /// Generate one codegen unit per source-level module.
125     PerModule,
126
127     /// Partition the whole crate into a fixed number of codegen units.
128     FixedUnitCount(usize)
129 }
130
131 pub trait CodegenUnitExt<'tcx> {
132     fn as_codegen_unit(&self) -> &CodegenUnit<'tcx>;
133
134     fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
135         self.items().contains_key(item)
136     }
137
138     fn name<'a>(&'a self) -> &'a InternedString
139         where 'tcx: 'a,
140     {
141         &self.as_codegen_unit().name()
142     }
143
144     fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
145         &self.as_codegen_unit().items()
146     }
147
148     fn work_product_id(&self) -> WorkProductId {
149         WorkProductId::from_cgu_name(self.name())
150     }
151
152     fn items_in_deterministic_order<'a>(&self,
153                                         tcx: TyCtxt<'a, 'tcx, 'tcx>)
154                                         -> Vec<(MonoItem<'tcx>,
155                                                 (Linkage, Visibility))> {
156         // The codegen tests rely on items being process in the same order as
157         // they appear in the file, so for local items, we sort by node_id first
158         #[derive(PartialEq, Eq, PartialOrd, Ord)]
159         pub struct ItemSortKey(Option<NodeId>, ty::SymbolName);
160
161         fn item_sort_key<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
162                                    item: MonoItem<'tcx>) -> ItemSortKey {
163             ItemSortKey(match item {
164                 MonoItem::Fn(ref instance) => {
165                     match instance.def {
166                         // We only want to take NodeIds of user-defined
167                         // instances into account. The others don't matter for
168                         // the codegen tests and can even make item order
169                         // unstable.
170                         InstanceDef::Item(def_id) => {
171                             tcx.hir.as_local_node_id(def_id)
172                         }
173                         InstanceDef::Intrinsic(..) |
174                         InstanceDef::FnPtrShim(..) |
175                         InstanceDef::Virtual(..) |
176                         InstanceDef::ClosureOnceShim { .. } |
177                         InstanceDef::DropGlue(..) |
178                         InstanceDef::CloneShim(..) => {
179                             None
180                         }
181                     }
182                 }
183                 MonoItem::Static(def_id) => {
184                     tcx.hir.as_local_node_id(def_id)
185                 }
186                 MonoItem::GlobalAsm(node_id) => {
187                     Some(node_id)
188                 }
189             }, item.symbol_name(tcx))
190         }
191
192         let items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
193         let mut items : Vec<_> = items.iter()
194             .map(|il| (il, item_sort_key(tcx, il.0))).collect();
195         items.sort_by(|&(_, ref key1), &(_, ref key2)| key1.cmp(key2));
196         items.into_iter().map(|(&item_linkage, _)| item_linkage).collect()
197     }
198 }
199
200 impl<'tcx> CodegenUnitExt<'tcx> for CodegenUnit<'tcx> {
201     fn as_codegen_unit(&self) -> &CodegenUnit<'tcx> {
202         self
203     }
204 }
205
206 // Anything we can't find a proper codegen unit for goes into this.
207 fn fallback_cgu_name(tcx: TyCtxt) -> InternedString {
208     const FALLBACK_CODEGEN_UNIT: &'static str = "__rustc_fallback_codegen_unit";
209
210     if tcx.sess.opts.debugging_opts.human_readable_cgu_names {
211         Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str()
212     } else {
213         Symbol::intern(&CodegenUnit::mangle_name(FALLBACK_CODEGEN_UNIT)).as_str()
214     }
215 }
216
217
218 pub fn partition<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
219                               trans_items: I,
220                               strategy: PartitioningStrategy,
221                               inlining_map: &InliningMap<'tcx>)
222                               -> Vec<CodegenUnit<'tcx>>
223     where I: Iterator<Item = MonoItem<'tcx>>
224 {
225     // In the first step, we place all regular translation items into their
226     // respective 'home' codegen unit. Regular translation items are all
227     // functions and statics defined in the local crate.
228     let mut initial_partitioning = place_root_translation_items(tcx,
229                                                                 trans_items);
230
231     initial_partitioning.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(&tcx));
232
233     debug_dump(tcx, "INITIAL PARTITIONING:", initial_partitioning.codegen_units.iter());
234
235     // If the partitioning should produce a fixed count of codegen units, merge
236     // until that count is reached.
237     if let PartitioningStrategy::FixedUnitCount(count) = strategy {
238         merge_codegen_units(&mut initial_partitioning, count, &tcx.crate_name.as_str());
239
240         debug_dump(tcx, "POST MERGING:", initial_partitioning.codegen_units.iter());
241     }
242
243     // In the next step, we use the inlining map to determine which additional
244     // translation items have to go into each codegen unit. These additional
245     // translation items can be drop-glue, functions from external crates, and
246     // local functions the definition of which is marked with #[inline].
247     let mut post_inlining = place_inlined_translation_items(initial_partitioning,
248                                                             inlining_map);
249
250     post_inlining.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(&tcx));
251
252     debug_dump(tcx, "POST INLINING:", post_inlining.codegen_units.iter());
253
254     // Next we try to make as many symbols "internal" as possible, so LLVM has
255     // more freedom to optimize.
256     if !tcx.sess.opts.cg.link_dead_code {
257         internalize_symbols(tcx, &mut post_inlining, inlining_map);
258     }
259
260     // Finally, sort by codegen unit name, so that we get deterministic results
261     let PostInliningPartitioning {
262         codegen_units: mut result,
263         trans_item_placements: _,
264         internalization_candidates: _,
265     } = post_inlining;
266
267     result.sort_by(|cgu1, cgu2| {
268         cgu1.name().cmp(cgu2.name())
269     });
270
271     result
272 }
273
274 struct PreInliningPartitioning<'tcx> {
275     codegen_units: Vec<CodegenUnit<'tcx>>,
276     roots: FxHashSet<MonoItem<'tcx>>,
277     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
278 }
279
280 /// For symbol internalization, we need to know whether a symbol/trans-item is
281 /// accessed from outside the codegen unit it is defined in. This type is used
282 /// to keep track of that.
283 #[derive(Clone, PartialEq, Eq, Debug)]
284 enum TransItemPlacement {
285     SingleCgu { cgu_name: InternedString },
286     MultipleCgus,
287 }
288
289 struct PostInliningPartitioning<'tcx> {
290     codegen_units: Vec<CodegenUnit<'tcx>>,
291     trans_item_placements: FxHashMap<MonoItem<'tcx>, TransItemPlacement>,
292     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
293 }
294
295 fn place_root_translation_items<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
296                                              trans_items: I)
297                                              -> PreInliningPartitioning<'tcx>
298     where I: Iterator<Item = MonoItem<'tcx>>
299 {
300     let mut roots = FxHashSet();
301     let mut codegen_units = FxHashMap();
302     let is_incremental_build = tcx.sess.opts.incremental.is_some();
303     let mut internalization_candidates = FxHashSet();
304
305     for trans_item in trans_items {
306         match trans_item.instantiation_mode(tcx) {
307             InstantiationMode::GloballyShared { .. } => {}
308             InstantiationMode::LocalCopy => continue,
309         }
310
311         let characteristic_def_id = characteristic_def_id_of_trans_item(tcx, trans_item);
312         let is_volatile = is_incremental_build &&
313                           trans_item.is_generic_fn();
314
315         let codegen_unit_name = match characteristic_def_id {
316             Some(def_id) => compute_codegen_unit_name(tcx, def_id, is_volatile),
317             None => fallback_cgu_name(tcx),
318         };
319
320         let make_codegen_unit = || {
321             CodegenUnit::new(codegen_unit_name.clone())
322         };
323
324         let codegen_unit = codegen_units.entry(codegen_unit_name.clone())
325                                             .or_insert_with(make_codegen_unit);
326
327         let mut can_be_internalized = true;
328         let default_visibility = |id: DefId| {
329             if tcx.sess.target.target.options.default_hidden_visibility &&
330                 tcx.symbol_export_level(id) != SymbolExportLevel::C
331             {
332                 Visibility::Hidden
333             } else {
334                 Visibility::Default
335             }
336         };
337         let (linkage, mut visibility) = match trans_item.explicit_linkage(tcx) {
338             Some(explicit_linkage) => (explicit_linkage, Visibility::Default),
339             None => {
340                 match trans_item {
341                     MonoItem::Fn(ref instance) => {
342                         let visibility = match instance.def {
343                             InstanceDef::Item(def_id) => {
344                                 // The `start_fn` lang item is actually a
345                                 // monomorphized instance of a function in the
346                                 // standard library, used for the `main`
347                                 // function. We don't want to export it so we
348                                 // tag it with `Hidden` visibility but this
349                                 // symbol is only referenced from the actual
350                                 // `main` symbol which we unfortunately don't
351                                 // know anything about during
352                                 // partitioning/collection. As a result we
353                                 // forcibly keep this symbol out of the
354                                 // `internalization_candidates` set.
355                                 //
356                                 // FIXME: eventually we don't want to always
357                                 // force this symbol to have hidden
358                                 // visibility, it should indeed be a candidate
359                                 // for internalization, but we have to
360                                 // understand that it's referenced from the
361                                 // `main` symbol we'll generate later.
362                                 if tcx.lang_items().start_fn() == Some(def_id) {
363                                     can_be_internalized = false;
364                                     Visibility::Hidden
365                                 } else if def_id.is_local() {
366                                     if tcx.is_reachable_non_generic(def_id) {
367                                         can_be_internalized = false;
368                                         default_visibility(def_id)
369                                     } else {
370                                         Visibility::Hidden
371                                     }
372                                 } else {
373                                     Visibility::Hidden
374                                 }
375                             }
376                             InstanceDef::FnPtrShim(..) |
377                             InstanceDef::Virtual(..) |
378                             InstanceDef::Intrinsic(..) |
379                             InstanceDef::ClosureOnceShim { .. } |
380                             InstanceDef::DropGlue(..) |
381                             InstanceDef::CloneShim(..) => {
382                                 Visibility::Hidden
383                             }
384                         };
385                         (Linkage::External, visibility)
386                     }
387                     MonoItem::Static(def_id) => {
388                         let visibility = if tcx.is_reachable_non_generic(def_id) {
389                             can_be_internalized = false;
390                             default_visibility(def_id)
391                         } else {
392                             Visibility::Hidden
393                         };
394                         (Linkage::External, visibility)
395                     }
396                     MonoItem::GlobalAsm(node_id) => {
397                         let def_id = tcx.hir.local_def_id(node_id);
398                         let visibility = if tcx.is_reachable_non_generic(def_id) {
399                             can_be_internalized = false;
400                             default_visibility(def_id)
401                         } else {
402                             Visibility::Hidden
403                         };
404                         (Linkage::External, visibility)
405                     }
406                 }
407             }
408         };
409         if visibility == Visibility::Hidden && can_be_internalized {
410             internalization_candidates.insert(trans_item);
411         }
412
413         codegen_unit.items_mut().insert(trans_item, (linkage, visibility));
414         roots.insert(trans_item);
415     }
416
417     // always ensure we have at least one CGU; otherwise, if we have a
418     // crate with just types (for example), we could wind up with no CGU
419     if codegen_units.is_empty() {
420         let codegen_unit_name = fallback_cgu_name(tcx);
421         codegen_units.insert(codegen_unit_name.clone(),
422                              CodegenUnit::new(codegen_unit_name.clone()));
423     }
424
425     PreInliningPartitioning {
426         codegen_units: codegen_units.into_iter()
427                                     .map(|(_, codegen_unit)| codegen_unit)
428                                     .collect(),
429         roots,
430         internalization_candidates,
431     }
432 }
433
434 fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<'tcx>,
435                              target_cgu_count: usize,
436                              crate_name: &str) {
437     assert!(target_cgu_count >= 1);
438     let codegen_units = &mut initial_partitioning.codegen_units;
439
440     // Note that at this point in time the `codegen_units` here may not be in a
441     // deterministic order (but we know they're deterministically the same set).
442     // We want this merging to produce a deterministic ordering of codegen units
443     // from the input.
444     //
445     // Due to basically how we've implemented the merging below (merge the two
446     // smallest into each other) we're sure to start off with a deterministic
447     // order (sorted by name). This'll mean that if two cgus have the same size
448     // the stable sort below will keep everything nice and deterministic.
449     codegen_units.sort_by_key(|cgu| cgu.name().clone());
450
451     // Merge the two smallest codegen units until the target size is reached.
452     while codegen_units.len() > target_cgu_count {
453         // Sort small cgus to the back
454         codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
455         let mut smallest = codegen_units.pop().unwrap();
456         let second_smallest = codegen_units.last_mut().unwrap();
457
458         second_smallest.modify_size_estimate(smallest.size_estimate());
459         for (k, v) in smallest.items_mut().drain() {
460             second_smallest.items_mut().insert(k, v);
461         }
462     }
463
464     for (index, cgu) in codegen_units.iter_mut().enumerate() {
465         cgu.set_name(numbered_codegen_unit_name(crate_name, index));
466     }
467 }
468
469 fn place_inlined_translation_items<'tcx>(initial_partitioning: PreInliningPartitioning<'tcx>,
470                                          inlining_map: &InliningMap<'tcx>)
471                                          -> PostInliningPartitioning<'tcx> {
472     let mut new_partitioning = Vec::new();
473     let mut trans_item_placements = FxHashMap();
474
475     let PreInliningPartitioning {
476         codegen_units: initial_cgus,
477         roots,
478         internalization_candidates,
479     } = initial_partitioning;
480
481     let single_codegen_unit = initial_cgus.len() == 1;
482
483     for old_codegen_unit in initial_cgus {
484         // Collect all items that need to be available in this codegen unit
485         let mut reachable = FxHashSet();
486         for root in old_codegen_unit.items().keys() {
487             follow_inlining(*root, inlining_map, &mut reachable);
488         }
489
490         let mut new_codegen_unit = CodegenUnit::new(old_codegen_unit.name().clone());
491
492         // Add all translation items that are not already there
493         for trans_item in reachable {
494             if let Some(linkage) = old_codegen_unit.items().get(&trans_item) {
495                 // This is a root, just copy it over
496                 new_codegen_unit.items_mut().insert(trans_item, *linkage);
497             } else {
498                 if roots.contains(&trans_item) {
499                     bug!("GloballyShared trans-item inlined into other CGU: \
500                           {:?}", trans_item);
501                 }
502
503                 // This is a cgu-private copy
504                 new_codegen_unit.items_mut().insert(
505                     trans_item,
506                     (Linkage::Internal, Visibility::Default),
507                 );
508             }
509
510             if !single_codegen_unit {
511                 // If there is more than one codegen unit, we need to keep track
512                 // in which codegen units each translation item is placed:
513                 match trans_item_placements.entry(trans_item) {
514                     Entry::Occupied(e) => {
515                         let placement = e.into_mut();
516                         debug_assert!(match *placement {
517                             TransItemPlacement::SingleCgu { ref cgu_name } => {
518                                 *cgu_name != *new_codegen_unit.name()
519                             }
520                             TransItemPlacement::MultipleCgus => true,
521                         });
522                         *placement = TransItemPlacement::MultipleCgus;
523                     }
524                     Entry::Vacant(e) => {
525                         e.insert(TransItemPlacement::SingleCgu {
526                             cgu_name: new_codegen_unit.name().clone()
527                         });
528                     }
529                 }
530             }
531         }
532
533         new_partitioning.push(new_codegen_unit);
534     }
535
536     return PostInliningPartitioning {
537         codegen_units: new_partitioning,
538         trans_item_placements,
539         internalization_candidates,
540     };
541
542     fn follow_inlining<'tcx>(trans_item: MonoItem<'tcx>,
543                              inlining_map: &InliningMap<'tcx>,
544                              visited: &mut FxHashSet<MonoItem<'tcx>>) {
545         if !visited.insert(trans_item) {
546             return;
547         }
548
549         inlining_map.with_inlining_candidates(trans_item, |target| {
550             follow_inlining(target, inlining_map, visited);
551         });
552     }
553 }
554
555 fn internalize_symbols<'a, 'tcx>(_tcx: TyCtxt<'a, 'tcx, 'tcx>,
556                                  partitioning: &mut PostInliningPartitioning<'tcx>,
557                                  inlining_map: &InliningMap<'tcx>) {
558     if partitioning.codegen_units.len() == 1 {
559         // Fast path for when there is only one codegen unit. In this case we
560         // can internalize all candidates, since there is nowhere else they
561         // could be accessed from.
562         for cgu in &mut partitioning.codegen_units {
563             for candidate in &partitioning.internalization_candidates {
564                 cgu.items_mut().insert(*candidate,
565                                        (Linkage::Internal, Visibility::Default));
566             }
567         }
568
569         return;
570     }
571
572     // Build a map from every translation item to all the translation items that
573     // reference it.
574     let mut accessor_map: FxHashMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>> = FxHashMap();
575     inlining_map.iter_accesses(|accessor, accessees| {
576         for accessee in accessees {
577             accessor_map.entry(*accessee)
578                         .or_insert(Vec::new())
579                         .push(accessor);
580         }
581     });
582
583     let trans_item_placements = &partitioning.trans_item_placements;
584
585     // For each internalization candidates in each codegen unit, check if it is
586     // accessed from outside its defining codegen unit.
587     for cgu in &mut partitioning.codegen_units {
588         let home_cgu = TransItemPlacement::SingleCgu {
589             cgu_name: cgu.name().clone()
590         };
591
592         for (accessee, linkage_and_visibility) in cgu.items_mut() {
593             if !partitioning.internalization_candidates.contains(accessee) {
594                 // This item is no candidate for internalizing, so skip it.
595                 continue
596             }
597             debug_assert_eq!(trans_item_placements[accessee], home_cgu);
598
599             if let Some(accessors) = accessor_map.get(accessee) {
600                 if accessors.iter()
601                             .filter_map(|accessor| {
602                                 // Some accessors might not have been
603                                 // instantiated. We can safely ignore those.
604                                 trans_item_placements.get(accessor)
605                             })
606                             .any(|placement| *placement != home_cgu) {
607                     // Found an accessor from another CGU, so skip to the next
608                     // item without marking this one as internal.
609                     continue
610                 }
611             }
612
613             // If we got here, we did not find any accesses from other CGUs,
614             // so it's fine to make this translation item internal.
615             *linkage_and_visibility = (Linkage::Internal, Visibility::Default);
616         }
617     }
618 }
619
620 fn characteristic_def_id_of_trans_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
621                                                  trans_item: MonoItem<'tcx>)
622                                                  -> Option<DefId> {
623     match trans_item {
624         MonoItem::Fn(instance) => {
625             let def_id = match instance.def {
626                 ty::InstanceDef::Item(def_id) => def_id,
627                 ty::InstanceDef::FnPtrShim(..) |
628                 ty::InstanceDef::ClosureOnceShim { .. } |
629                 ty::InstanceDef::Intrinsic(..) |
630                 ty::InstanceDef::DropGlue(..) |
631                 ty::InstanceDef::Virtual(..) |
632                 ty::InstanceDef::CloneShim(..) => return None
633             };
634
635             // If this is a method, we want to put it into the same module as
636             // its self-type. If the self-type does not provide a characteristic
637             // DefId, we use the location of the impl after all.
638
639             if tcx.trait_of_item(def_id).is_some() {
640                 let self_ty = instance.substs.type_at(0);
641                 // This is an implementation of a trait method.
642                 return characteristic_def_id_of_type(self_ty).or(Some(def_id));
643             }
644
645             if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
646                 // This is a method within an inherent impl, find out what the
647                 // self-type is:
648                 let impl_self_ty = tcx.trans_impl_self_ty(impl_def_id, instance.substs);
649                 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
650                     return Some(def_id);
651                 }
652             }
653
654             Some(def_id)
655         }
656         MonoItem::Static(def_id) => Some(def_id),
657         MonoItem::GlobalAsm(node_id) => Some(tcx.hir.local_def_id(node_id)),
658     }
659 }
660
661 fn compute_codegen_unit_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
662                                        def_id: DefId,
663                                        volatile: bool)
664                                        -> InternedString {
665     // Unfortunately we cannot just use the `ty::item_path` infrastructure here
666     // because we need paths to modules and the DefIds of those are not
667     // available anymore for external items.
668     let mut cgu_name = String::with_capacity(64);
669
670     let def_path = tcx.def_path(def_id);
671     cgu_name.push_str(&tcx.crate_name(def_path.krate).as_str());
672
673     for part in tcx.def_path(def_id)
674                    .data
675                    .iter()
676                    .take_while(|part| {
677                         match part.data {
678                             DefPathData::Module(..) => true,
679                             _ => false,
680                         }
681                     }) {
682         cgu_name.push_str("-");
683         cgu_name.push_str(&part.data.as_interned_str());
684     }
685
686     if volatile {
687         cgu_name.push_str(".volatile");
688     }
689
690     let cgu_name = if tcx.sess.opts.debugging_opts.human_readable_cgu_names {
691         cgu_name
692     } else {
693         CodegenUnit::mangle_name(&cgu_name)
694     };
695
696     Symbol::intern(&cgu_name[..]).as_str()
697 }
698
699 fn numbered_codegen_unit_name(crate_name: &str, index: usize) -> InternedString {
700     Symbol::intern(&format!("{}{}", crate_name, index)).as_str()
701 }
702
703 fn debug_dump<'a, 'b, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
704                                label: &str,
705                                cgus: I)
706     where I: Iterator<Item=&'b CodegenUnit<'tcx>>,
707           'tcx: 'a + 'b
708 {
709     if cfg!(debug_assertions) {
710         debug!("{}", label);
711         for cgu in cgus {
712             debug!("CodegenUnit {}:", cgu.name());
713
714             for (trans_item, linkage) in cgu.items() {
715                 let symbol_name = trans_item.symbol_name(tcx);
716                 let symbol_hash_start = symbol_name.rfind('h');
717                 let symbol_hash = symbol_hash_start.map(|i| &symbol_name[i ..])
718                                                    .unwrap_or("<no hash>");
719
720                 debug!(" - {} [{:?}] [{}]",
721                        trans_item.to_string(tcx),
722                        linkage,
723                        symbol_hash);
724             }
725
726             debug!("");
727         }
728     }
729 }