]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/partitioning.rs
Fixed all unnecessary muts in language core
[rust.git] / src / librustc_trans / 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 back::symbol_export::ExportedSymbols;
106 use collector::InliningMap;
107 use common;
108 use context::SharedCrateContext;
109 use llvm;
110 use rustc::dep_graph::{DepNode, WorkProductId};
111 use rustc::hir::def_id::DefId;
112 use rustc::hir::map::DefPathData;
113 use rustc::session::config::NUMBERED_CODEGEN_UNIT_MARKER;
114 use rustc::ty::{self, TyCtxt, InstanceDef};
115 use rustc::ty::item_path::characteristic_def_id_of_type;
116 use rustc::util::nodemap::{FxHashMap, FxHashSet};
117 use rustc_incremental::IchHasher;
118 use std::collections::hash_map::Entry;
119 use std::hash::Hash;
120 use syntax::ast::NodeId;
121 use syntax::symbol::{Symbol, InternedString};
122 use trans_item::{TransItem, InstantiationMode};
123
124 pub enum PartitioningStrategy {
125     /// Generate one codegen unit per source-level module.
126     PerModule,
127
128     /// Partition the whole crate into a fixed number of codegen units.
129     FixedUnitCount(usize)
130 }
131
132 pub struct CodegenUnit<'tcx> {
133     /// A name for this CGU. Incremental compilation requires that
134     /// name be unique amongst **all** crates.  Therefore, it should
135     /// contain something unique to this crate (e.g., a module path)
136     /// as well as the crate name and disambiguator.
137     name: InternedString,
138
139     items: FxHashMap<TransItem<'tcx>, (llvm::Linkage, llvm::Visibility)>,
140 }
141
142 impl<'tcx> CodegenUnit<'tcx> {
143     pub fn new(name: InternedString,
144                items: FxHashMap<TransItem<'tcx>, (llvm::Linkage, llvm::Visibility)>)
145                -> Self {
146         CodegenUnit {
147             name,
148             items,
149         }
150     }
151
152     pub fn empty(name: InternedString) -> Self {
153         Self::new(name, FxHashMap())
154     }
155
156     pub fn contains_item(&self, item: &TransItem<'tcx>) -> bool {
157         self.items.contains_key(item)
158     }
159
160     pub fn name(&self) -> &str {
161         &self.name
162     }
163
164     pub fn items(&self) -> &FxHashMap<TransItem<'tcx>, (llvm::Linkage, llvm::Visibility)> {
165         &self.items
166     }
167
168     pub fn work_product_id(&self) -> WorkProductId {
169         WorkProductId::from_cgu_name(self.name())
170     }
171
172     pub fn work_product_dep_node(&self) -> DepNode {
173         self.work_product_id().to_dep_node()
174     }
175
176     pub fn compute_symbol_name_hash<'a>(&self,
177                                         scx: &SharedCrateContext<'a, 'tcx>,
178                                         exported_symbols: &ExportedSymbols)
179                                         -> u64 {
180         let mut state = IchHasher::new();
181         let exported_symbols = exported_symbols.local_exports();
182         let all_items = self.items_in_deterministic_order(scx.tcx());
183         for (item, _) in all_items {
184             let symbol_name = item.symbol_name(scx.tcx());
185             symbol_name.len().hash(&mut state);
186             symbol_name.hash(&mut state);
187             let exported = match item {
188                 TransItem::Fn(ref instance) => {
189                     let node_id =
190                         scx.tcx().hir.as_local_node_id(instance.def_id());
191                     node_id.map(|node_id| exported_symbols.contains(&node_id))
192                         .unwrap_or(false)
193                 }
194                 TransItem::Static(node_id) => {
195                     exported_symbols.contains(&node_id)
196                 }
197                 TransItem::GlobalAsm(..) => true,
198             };
199             exported.hash(&mut state);
200         }
201         state.finish().to_smaller_hash()
202     }
203
204     pub fn items_in_deterministic_order<'a>(&self,
205                                             tcx: TyCtxt<'a, 'tcx, 'tcx>)
206                                             -> Vec<(TransItem<'tcx>,
207                                                    (llvm::Linkage, llvm::Visibility))> {
208         // The codegen tests rely on items being process in the same order as
209         // they appear in the file, so for local items, we sort by node_id first
210         #[derive(PartialEq, Eq, PartialOrd, Ord)]
211         pub struct ItemSortKey(Option<NodeId>, ty::SymbolName);
212
213         fn item_sort_key<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
214                                    item: TransItem<'tcx>) -> ItemSortKey {
215             ItemSortKey(match item {
216                 TransItem::Fn(instance) => {
217                     tcx.hir.as_local_node_id(instance.def_id())
218                 }
219                 TransItem::Static(node_id) | TransItem::GlobalAsm(node_id) => {
220                     Some(node_id)
221                 }
222             }, item.symbol_name(tcx))
223         }
224
225         let items: Vec<_> = self.items.iter().map(|(&i, &l)| (i, l)).collect();
226         let mut items : Vec<_> = items.iter()
227             .map(|il| (il, item_sort_key(tcx, il.0))).collect();
228         items.sort_by(|&(_, ref key1), &(_, ref key2)| key1.cmp(key2));
229         items.into_iter().map(|(&item_linkage, _)| item_linkage).collect()
230     }
231 }
232
233
234 // Anything we can't find a proper codegen unit for goes into this.
235 const FALLBACK_CODEGEN_UNIT: &'static str = "__rustc_fallback_codegen_unit";
236
237 pub fn partition<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
238                               trans_items: I,
239                               strategy: PartitioningStrategy,
240                               inlining_map: &InliningMap<'tcx>,
241                               exported_symbols: &ExportedSymbols)
242                               -> Vec<CodegenUnit<'tcx>>
243     where I: Iterator<Item = TransItem<'tcx>>
244 {
245     let tcx = scx.tcx();
246
247     // In the first step, we place all regular translation items into their
248     // respective 'home' codegen unit. Regular translation items are all
249     // functions and statics defined in the local crate.
250     let mut initial_partitioning = place_root_translation_items(scx,
251                                                                 exported_symbols,
252                                                                 trans_items);
253
254     debug_dump(tcx, "INITIAL PARTITIONING:", initial_partitioning.codegen_units.iter());
255
256     // If the partitioning should produce a fixed count of codegen units, merge
257     // until that count is reached.
258     if let PartitioningStrategy::FixedUnitCount(count) = strategy {
259         merge_codegen_units(&mut initial_partitioning, count, &tcx.crate_name.as_str());
260
261         debug_dump(tcx, "POST MERGING:", initial_partitioning.codegen_units.iter());
262     }
263
264     // In the next step, we use the inlining map to determine which additional
265     // translation items have to go into each codegen unit. These additional
266     // translation items can be drop-glue, functions from external crates, and
267     // local functions the definition of which is marked with #[inline].
268     let mut post_inlining = place_inlined_translation_items(initial_partitioning,
269                                                             inlining_map);
270
271     debug_dump(tcx, "POST INLINING:", post_inlining.codegen_units.iter());
272
273     // Next we try to make as many symbols "internal" as possible, so LLVM has
274     // more freedom to optimize.
275     internalize_symbols(tcx, &mut post_inlining, inlining_map);
276
277     // Finally, sort by codegen unit name, so that we get deterministic results
278     let PostInliningPartitioning {
279         codegen_units: mut result,
280         trans_item_placements: _,
281         internalization_candidates: _,
282     } = post_inlining;
283
284     result.sort_by(|cgu1, cgu2| {
285         (&cgu1.name[..]).cmp(&cgu2.name[..])
286     });
287
288     if scx.sess().opts.enable_dep_node_debug_strs() {
289         for cgu in &result {
290             let dep_node = cgu.work_product_dep_node();
291             scx.tcx().dep_graph.register_dep_node_debug_str(dep_node,
292                                                             || cgu.name().to_string());
293         }
294     }
295
296     result
297 }
298
299 struct PreInliningPartitioning<'tcx> {
300     codegen_units: Vec<CodegenUnit<'tcx>>,
301     roots: FxHashSet<TransItem<'tcx>>,
302     internalization_candidates: FxHashSet<TransItem<'tcx>>,
303 }
304
305 /// For symbol internalization, we need to know whether a symbol/trans-item is
306 /// accessed from outside the codegen unit it is defined in. This type is used
307 /// to keep track of that.
308 #[derive(Clone, PartialEq, Eq, Debug)]
309 enum TransItemPlacement {
310     SingleCgu { cgu_name: InternedString },
311     MultipleCgus,
312 }
313
314 struct PostInliningPartitioning<'tcx> {
315     codegen_units: Vec<CodegenUnit<'tcx>>,
316     trans_item_placements: FxHashMap<TransItem<'tcx>, TransItemPlacement>,
317     internalization_candidates: FxHashSet<TransItem<'tcx>>,
318 }
319
320 fn place_root_translation_items<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
321                                              exported_symbols: &ExportedSymbols,
322                                              trans_items: I)
323                                              -> PreInliningPartitioning<'tcx>
324     where I: Iterator<Item = TransItem<'tcx>>
325 {
326     let tcx = scx.tcx();
327     let exported_symbols = exported_symbols.local_exports();
328
329     let mut roots = FxHashSet();
330     let mut codegen_units = FxHashMap();
331     let is_incremental_build = tcx.sess.opts.incremental.is_some();
332     let mut internalization_candidates = FxHashSet();
333
334     for trans_item in trans_items {
335         let is_root = trans_item.instantiation_mode(tcx) == InstantiationMode::GloballyShared;
336
337         if is_root {
338             let characteristic_def_id = characteristic_def_id_of_trans_item(scx, trans_item);
339             let is_volatile = is_incremental_build &&
340                               trans_item.is_generic_fn();
341
342             let codegen_unit_name = match characteristic_def_id {
343                 Some(def_id) => compute_codegen_unit_name(tcx, def_id, is_volatile),
344                 None => Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str(),
345             };
346
347             let make_codegen_unit = || {
348                 CodegenUnit::empty(codegen_unit_name.clone())
349             };
350
351             let codegen_unit = codegen_units.entry(codegen_unit_name.clone())
352                                                 .or_insert_with(make_codegen_unit);
353
354             let (linkage, visibility) = match trans_item.explicit_linkage(tcx) {
355                 Some(explicit_linkage) => (explicit_linkage, llvm::Visibility::Default),
356                 None => {
357                     match trans_item {
358                         TransItem::Fn(ref instance) => {
359                             let visibility = match instance.def {
360                                 InstanceDef::Item(def_id) => {
361                                     if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
362                                         if exported_symbols.contains(&node_id) {
363                                             llvm::Visibility::Default
364                                         } else {
365                                             internalization_candidates.insert(trans_item);
366                                             llvm::Visibility::Hidden
367                                         }
368                                     } else {
369                                         internalization_candidates.insert(trans_item);
370                                         llvm::Visibility::Hidden
371                                     }
372                                 }
373                                 InstanceDef::FnPtrShim(..) |
374                                 InstanceDef::Virtual(..) |
375                                 InstanceDef::Intrinsic(..) |
376                                 InstanceDef::ClosureOnceShim { .. } |
377                                 InstanceDef::DropGlue(..) => {
378                                     bug!("partitioning: Encountered unexpected
379                                           root translation item: {:?}",
380                                           trans_item)
381                                 }
382                             };
383                             (llvm::ExternalLinkage, visibility)
384                         }
385                         TransItem::Static(node_id) |
386                         TransItem::GlobalAsm(node_id) => {
387                             let visibility = if exported_symbols.contains(&node_id) {
388                                 llvm::Visibility::Default
389                             } else {
390                                 internalization_candidates.insert(trans_item);
391                                 llvm::Visibility::Hidden
392                             };
393                             (llvm::ExternalLinkage, visibility)
394                         }
395                     }
396                 }
397             };
398
399             codegen_unit.items.insert(trans_item, (linkage, visibility));
400             roots.insert(trans_item);
401         }
402     }
403
404     // always ensure we have at least one CGU; otherwise, if we have a
405     // crate with just types (for example), we could wind up with no CGU
406     if codegen_units.is_empty() {
407         let codegen_unit_name = Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str();
408         codegen_units.insert(codegen_unit_name.clone(),
409                              CodegenUnit::empty(codegen_unit_name.clone()));
410     }
411
412     PreInliningPartitioning {
413         codegen_units: codegen_units.into_iter()
414                                     .map(|(_, codegen_unit)| codegen_unit)
415                                     .collect(),
416         roots,
417         internalization_candidates,
418     }
419 }
420
421 fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<'tcx>,
422                              target_cgu_count: usize,
423                              crate_name: &str) {
424     assert!(target_cgu_count >= 1);
425     let codegen_units = &mut initial_partitioning.codegen_units;
426
427     // Merge the two smallest codegen units until the target size is reached.
428     // Note that "size" is estimated here rather inaccurately as the number of
429     // translation items in a given unit. This could be improved on.
430     while codegen_units.len() > target_cgu_count {
431         // Sort small cgus to the back
432         codegen_units.sort_by_key(|cgu| -(cgu.items.len() as i64));
433         let smallest = codegen_units.pop().unwrap();
434         let second_smallest = codegen_units.last_mut().unwrap();
435
436         for (k, v) in smallest.items.into_iter() {
437             second_smallest.items.insert(k, v);
438         }
439     }
440
441     for (index, cgu) in codegen_units.iter_mut().enumerate() {
442         cgu.name = numbered_codegen_unit_name(crate_name, index);
443     }
444
445     // If the initial partitioning contained less than target_cgu_count to begin
446     // with, we won't have enough codegen units here, so add a empty units until
447     // we reach the target count
448     while codegen_units.len() < target_cgu_count {
449         let index = codegen_units.len();
450         codegen_units.push(
451             CodegenUnit::empty(numbered_codegen_unit_name(crate_name, index)));
452     }
453 }
454
455 fn place_inlined_translation_items<'tcx>(initial_partitioning: PreInliningPartitioning<'tcx>,
456                                          inlining_map: &InliningMap<'tcx>)
457                                          -> PostInliningPartitioning<'tcx> {
458     let mut new_partitioning = Vec::new();
459     let mut trans_item_placements = FxHashMap();
460
461     let PreInliningPartitioning {
462         codegen_units: initial_cgus,
463         roots,
464         internalization_candidates,
465     } = initial_partitioning;
466
467     let single_codegen_unit = initial_cgus.len() == 1;
468
469     for old_codegen_unit in initial_cgus {
470         // Collect all items that need to be available in this codegen unit
471         let mut reachable = FxHashSet();
472         for root in old_codegen_unit.items.keys() {
473             follow_inlining(*root, inlining_map, &mut reachable);
474         }
475
476         let mut new_codegen_unit = CodegenUnit {
477             name: old_codegen_unit.name,
478             items: FxHashMap(),
479         };
480
481         // Add all translation items that are not already there
482         for trans_item in reachable {
483             if let Some(linkage) = old_codegen_unit.items.get(&trans_item) {
484                 // This is a root, just copy it over
485                 new_codegen_unit.items.insert(trans_item, *linkage);
486             } else {
487                 if roots.contains(&trans_item) {
488                     bug!("GloballyShared trans-item inlined into other CGU: \
489                           {:?}", trans_item);
490                 }
491
492                 // This is a cgu-private copy
493                 new_codegen_unit.items.insert(trans_item,
494                                               (llvm::InternalLinkage, llvm::Visibility::Default));
495             }
496
497             if !single_codegen_unit {
498                 // If there is more than one codegen unit, we need to keep track
499                 // in which codegen units each translation item is placed:
500                 match trans_item_placements.entry(trans_item) {
501                     Entry::Occupied(e) => {
502                         let placement = e.into_mut();
503                         debug_assert!(match *placement {
504                             TransItemPlacement::SingleCgu { ref cgu_name } => {
505                                 *cgu_name != new_codegen_unit.name
506                             }
507                             TransItemPlacement::MultipleCgus => true,
508                         });
509                         *placement = TransItemPlacement::MultipleCgus;
510                     }
511                     Entry::Vacant(e) => {
512                         e.insert(TransItemPlacement::SingleCgu {
513                             cgu_name: new_codegen_unit.name.clone()
514                         });
515                     }
516                 }
517             }
518         }
519
520         new_partitioning.push(new_codegen_unit);
521     }
522
523     return PostInliningPartitioning {
524         codegen_units: new_partitioning,
525         trans_item_placements,
526         internalization_candidates,
527     };
528
529     fn follow_inlining<'tcx>(trans_item: TransItem<'tcx>,
530                              inlining_map: &InliningMap<'tcx>,
531                              visited: &mut FxHashSet<TransItem<'tcx>>) {
532         if !visited.insert(trans_item) {
533             return;
534         }
535
536         inlining_map.with_inlining_candidates(trans_item, |target| {
537             follow_inlining(target, inlining_map, visited);
538         });
539     }
540 }
541
542 fn internalize_symbols<'a, 'tcx>(_tcx: TyCtxt<'a, 'tcx, 'tcx>,
543                                  partitioning: &mut PostInliningPartitioning<'tcx>,
544                                  inlining_map: &InliningMap<'tcx>) {
545     if partitioning.codegen_units.len() == 1 {
546         // Fast path for when there is only one codegen unit. In this case we
547         // can internalize all candidates, since there is nowhere else they
548         // could be accessed from.
549         for cgu in &mut partitioning.codegen_units {
550             for candidate in &partitioning.internalization_candidates {
551                 cgu.items.insert(*candidate, (llvm::InternalLinkage,
552                                               llvm::Visibility::Default));
553             }
554         }
555
556         return;
557     }
558
559     // Build a map from every translation item to all the translation items that
560     // reference it.
561     let mut accessor_map: FxHashMap<TransItem<'tcx>, Vec<TransItem<'tcx>>> = FxHashMap();
562     inlining_map.iter_accesses(|accessor, accessees| {
563         for accessee in accessees {
564             accessor_map.entry(*accessee)
565                         .or_insert(Vec::new())
566                         .push(accessor);
567         }
568     });
569
570     let trans_item_placements = &partitioning.trans_item_placements;
571
572     // For each internalization candidates in each codegen unit, check if it is
573     // accessed from outside its defining codegen unit.
574     for cgu in &mut partitioning.codegen_units {
575         let home_cgu = TransItemPlacement::SingleCgu {
576             cgu_name: cgu.name.clone()
577         };
578
579         for (accessee, linkage_and_visibility) in &mut cgu.items {
580             if !partitioning.internalization_candidates.contains(accessee) {
581                 // This item is no candidate for internalizing, so skip it.
582                 continue
583             }
584             debug_assert_eq!(trans_item_placements[accessee], home_cgu);
585
586             if let Some(accessors) = accessor_map.get(accessee) {
587                 if accessors.iter()
588                             .filter_map(|accessor| {
589                                 // Some accessors might not have been
590                                 // instantiated. We can safely ignore those.
591                                 trans_item_placements.get(accessor)
592                             })
593                             .any(|placement| *placement != home_cgu) {
594                     // Found an accessor from another CGU, so skip to the next
595                     // item without marking this one as internal.
596                     continue
597                 }
598             }
599
600             // If we got here, we did not find any accesses from other CGUs,
601             // so it's fine to make this translation item internal.
602             *linkage_and_visibility = (llvm::InternalLinkage, llvm::Visibility::Default);
603         }
604     }
605 }
606
607 fn characteristic_def_id_of_trans_item<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
608                                                  trans_item: TransItem<'tcx>)
609                                                  -> Option<DefId> {
610     let tcx = scx.tcx();
611     match trans_item {
612         TransItem::Fn(instance) => {
613             let def_id = match instance.def {
614                 ty::InstanceDef::Item(def_id) => def_id,
615                 ty::InstanceDef::FnPtrShim(..) |
616                 ty::InstanceDef::ClosureOnceShim { .. } |
617                 ty::InstanceDef::Intrinsic(..) |
618                 ty::InstanceDef::DropGlue(..) |
619                 ty::InstanceDef::Virtual(..) => return None
620             };
621
622             // If this is a method, we want to put it into the same module as
623             // its self-type. If the self-type does not provide a characteristic
624             // DefId, we use the location of the impl after all.
625
626             if tcx.trait_of_item(def_id).is_some() {
627                 let self_ty = instance.substs.type_at(0);
628                 // This is an implementation of a trait method.
629                 return characteristic_def_id_of_type(self_ty).or(Some(def_id));
630             }
631
632             if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
633                 // This is a method within an inherent impl, find out what the
634                 // self-type is:
635                 let impl_self_ty = common::def_ty(scx, impl_def_id, instance.substs);
636                 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
637                     return Some(def_id);
638                 }
639             }
640
641             Some(def_id)
642         }
643         TransItem::Static(node_id) |
644         TransItem::GlobalAsm(node_id) => Some(tcx.hir.local_def_id(node_id)),
645     }
646 }
647
648 fn compute_codegen_unit_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
649                                        def_id: DefId,
650                                        volatile: bool)
651                                        -> InternedString {
652     // Unfortunately we cannot just use the `ty::item_path` infrastructure here
653     // because we need paths to modules and the DefIds of those are not
654     // available anymore for external items.
655     let mut mod_path = String::with_capacity(64);
656
657     let def_path = tcx.def_path(def_id);
658     mod_path.push_str(&tcx.crate_name(def_path.krate).as_str());
659
660     for part in tcx.def_path(def_id)
661                    .data
662                    .iter()
663                    .take_while(|part| {
664                         match part.data {
665                             DefPathData::Module(..) => true,
666                             _ => false,
667                         }
668                     }) {
669         mod_path.push_str("-");
670         mod_path.push_str(&part.data.as_interned_str());
671     }
672
673     if volatile {
674         mod_path.push_str(".volatile");
675     }
676
677     return Symbol::intern(&mod_path[..]).as_str();
678 }
679
680 fn numbered_codegen_unit_name(crate_name: &str, index: usize) -> InternedString {
681     Symbol::intern(&format!("{}{}{}", crate_name, NUMBERED_CODEGEN_UNIT_MARKER, index)).as_str()
682 }
683
684 fn debug_dump<'a, 'b, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
685                                label: &str,
686                                cgus: I)
687     where I: Iterator<Item=&'b CodegenUnit<'tcx>>,
688           'tcx: 'a + 'b
689 {
690     if cfg!(debug_assertions) {
691         debug!("{}", label);
692         for cgu in cgus {
693             debug!("CodegenUnit {}:", cgu.name);
694
695             for (trans_item, linkage) in &cgu.items {
696                 let symbol_name = trans_item.symbol_name(tcx);
697                 let symbol_hash_start = symbol_name.rfind('h');
698                 let symbol_hash = symbol_hash_start.map(|i| &symbol_name[i ..])
699                                                    .unwrap_or("<no hash>");
700
701                 debug!(" - {} [{:?}] [{}]",
702                        trans_item.to_string(tcx),
703                        linkage,
704                        symbol_hash);
705             }
706
707             debug!("");
708         }
709     }
710 }