Skip to content

Commit 621bf0d

Browse files
committed
move monoitemext to inherent methods
1 parent f2b9b2d commit 621bf0d

File tree

7 files changed

+211
-28
lines changed

7 files changed

+211
-28
lines changed

src/librustc/mir/mono.rs

Lines changed: 190 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,44 @@
11
use crate::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
22
use crate::hir::HirId;
33
use syntax::symbol::InternedString;
4-
use crate::ty::{Instance, TyCtxt};
4+
use syntax::attr::InlineAttr;
5+
use syntax::source_map::Span;
6+
use crate::ty::{Instance, TyCtxt, SymbolName, subst::InternalSubsts};
57
use crate::util::nodemap::FxHashMap;
8+
use crate::ty::print::obsolete::DefPathBasedNames;
69
use rustc_data_structures::base_n;
710
use rustc_data_structures::stable_hasher::{HashStable, StableHasherResult,
811
StableHasher};
912
use crate::ich::{Fingerprint, StableHashingContext, NodeIdHashingMode};
13+
use crate::session::config::OptLevel;
1014
use std::fmt;
1115
use std::hash::Hash;
1216

17+
/// Describes how a monomorphization will be instantiated in object files.
18+
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
19+
pub enum InstantiationMode {
20+
/// There will be exactly one instance of the given MonoItem. It will have
21+
/// external linkage so that it can be linked to from other codegen units.
22+
GloballyShared {
23+
/// In some compilation scenarios we may decide to take functions that
24+
/// are typically `LocalCopy` and instead move them to `GloballyShared`
25+
/// to avoid codegenning them a bunch of times. In this situation,
26+
/// however, our local copy may conflict with other crates also
27+
/// inlining the same function.
28+
///
29+
/// This flag indicates that this situation is occurring, and informs
30+
/// symbol name calculation that some extra mangling is needed to
31+
/// avoid conflicts. Note that this may eventually go away entirely if
32+
/// ThinLTO enables us to *always* have a globally shared instance of a
33+
/// function within one crate's compilation.
34+
may_conflict: bool,
35+
},
36+
37+
/// Each codegen unit containing a reference to the given MonoItem will
38+
/// have its own private copy of the function (with internal linkage).
39+
LocalCopy,
40+
}
41+
1342
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
1443
pub enum MonoItem<'tcx> {
1544
Fn(Instance<'tcx>),
@@ -31,6 +60,166 @@ impl<'tcx> MonoItem<'tcx> {
3160
MonoItem::GlobalAsm(_) => 1,
3261
}
3362
}
63+
64+
pub fn is_generic_fn(&self) -> bool {
65+
match *self {
66+
MonoItem::Fn(ref instance) => {
67+
instance.substs.non_erasable_generics().next().is_some()
68+
}
69+
MonoItem::Static(..) |
70+
MonoItem::GlobalAsm(..) => false,
71+
}
72+
}
73+
74+
pub fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> SymbolName {
75+
match *self {
76+
MonoItem::Fn(instance) => tcx.symbol_name(instance),
77+
MonoItem::Static(def_id) => {
78+
tcx.symbol_name(Instance::mono(tcx, def_id))
79+
}
80+
MonoItem::GlobalAsm(hir_id) => {
81+
let def_id = tcx.hir().local_def_id_from_hir_id(hir_id);
82+
SymbolName {
83+
name: InternedString::intern(&format!("global_asm_{:?}", def_id))
84+
}
85+
}
86+
}
87+
}
88+
89+
pub fn instantiation_mode(&self,
90+
tcx: TyCtxt<'a, 'tcx, 'tcx>)
91+
-> InstantiationMode {
92+
let inline_in_all_cgus =
93+
tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
94+
tcx.sess.opts.optimize != OptLevel::No
95+
}) && !tcx.sess.opts.cg.link_dead_code;
96+
97+
match *self {
98+
MonoItem::Fn(ref instance) => {
99+
let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id);
100+
// If this function isn't inlined or otherwise has explicit
101+
// linkage, then we'll be creating a globally shared version.
102+
if self.explicit_linkage(tcx).is_some() ||
103+
!instance.def.requires_local(tcx) ||
104+
Some(instance.def_id()) == entry_def_id
105+
{
106+
return InstantiationMode::GloballyShared { may_conflict: false }
107+
}
108+
109+
// At this point we don't have explicit linkage and we're an
110+
// inlined function. If we're inlining into all CGUs then we'll
111+
// be creating a local copy per CGU
112+
if inline_in_all_cgus {
113+
return InstantiationMode::LocalCopy
114+
}
115+
116+
// Finally, if this is `#[inline(always)]` we're sure to respect
117+
// that with an inline copy per CGU, but otherwise we'll be
118+
// creating one copy of this `#[inline]` function which may
119+
// conflict with upstream crates as it could be an exported
120+
// symbol.
121+
match tcx.codegen_fn_attrs(instance.def_id()).inline {
122+
InlineAttr::Always => InstantiationMode::LocalCopy,
123+
_ => {
124+
InstantiationMode::GloballyShared { may_conflict: true }
125+
}
126+
}
127+
}
128+
MonoItem::Static(..) |
129+
MonoItem::GlobalAsm(..) => {
130+
InstantiationMode::GloballyShared { may_conflict: false }
131+
}
132+
}
133+
}
134+
135+
pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Linkage> {
136+
let def_id = match *self {
137+
MonoItem::Fn(ref instance) => instance.def_id(),
138+
MonoItem::Static(def_id) => def_id,
139+
MonoItem::GlobalAsm(..) => return None,
140+
};
141+
142+
let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
143+
codegen_fn_attrs.linkage
144+
}
145+
146+
/// Returns `true` if this instance is instantiable - whether it has no unsatisfied
147+
/// predicates.
148+
///
149+
/// In order to codegen an item, all of its predicates must hold, because
150+
/// otherwise the item does not make sense. Type-checking ensures that
151+
/// the predicates of every item that is *used by* a valid item *do*
152+
/// hold, so we can rely on that.
153+
///
154+
/// However, we codegen collector roots (reachable items) and functions
155+
/// in vtables when they are seen, even if they are not used, and so they
156+
/// might not be instantiable. For example, a programmer can define this
157+
/// public function:
158+
///
159+
/// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
160+
/// <&mut () as Clone>::clone(&s);
161+
/// }
162+
///
163+
/// That function can't be codegened, because the method `<&mut () as Clone>::clone`
164+
/// does not exist. Luckily for us, that function can't ever be used,
165+
/// because that would require for `&'a mut (): Clone` to hold, so we
166+
/// can just not emit any code, or even a linker reference for it.
167+
///
168+
/// Similarly, if a vtable method has such a signature, and therefore can't
169+
/// be used, we can just not emit it and have a placeholder (a null pointer,
170+
/// which will never be accessed) in its place.
171+
pub fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
172+
debug!("is_instantiable({:?})", self);
173+
let (def_id, substs) = match *self {
174+
MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
175+
MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
176+
// global asm never has predicates
177+
MonoItem::GlobalAsm(..) => return true
178+
};
179+
180+
tcx.substitute_normalize_and_test_predicates((def_id, &substs))
181+
}
182+
183+
pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, debug: bool) -> String {
184+
return match *self {
185+
MonoItem::Fn(instance) => {
186+
to_string_internal(tcx, "fn ", instance, debug)
187+
},
188+
MonoItem::Static(def_id) => {
189+
let instance = Instance::new(def_id, tcx.intern_substs(&[]));
190+
to_string_internal(tcx, "static ", instance, debug)
191+
},
192+
MonoItem::GlobalAsm(..) => {
193+
"global_asm".to_string()
194+
}
195+
};
196+
197+
fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
198+
prefix: &str,
199+
instance: Instance<'tcx>,
200+
debug: bool)
201+
-> String {
202+
let mut result = String::with_capacity(32);
203+
result.push_str(prefix);
204+
let printer = DefPathBasedNames::new(tcx, false, false);
205+
printer.push_instance_as_string(instance, &mut result, debug);
206+
result
207+
}
208+
}
209+
210+
pub fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
211+
match *self {
212+
MonoItem::Fn(Instance { def, .. }) => {
213+
tcx.hir().as_local_hir_id(def.def_id())
214+
}
215+
MonoItem::Static(def_id) => {
216+
tcx.hir().as_local_hir_id(def_id)
217+
}
218+
MonoItem::GlobalAsm(hir_id) => {
219+
Some(hir_id)
220+
}
221+
}.map(|hir_id| tcx.hir().span_by_hir_id(hir_id))
222+
}
34223
}
35224

36225
impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {

src/librustc_codegen_ssa/base.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,10 @@ use rustc::hir::def_id::{DefId, LOCAL_CRATE};
2020
use rustc::middle::cstore::EncodedMetadata;
2121
use rustc::middle::lang_items::StartFnLangItem;
2222
use rustc::middle::weak_lang_items;
23-
use rustc::mir::mono::{CodegenUnitNameBuilder, CodegenUnit};
23+
use rustc::mir::mono::{CodegenUnitNameBuilder, CodegenUnit, MonoItem};
2424
use rustc::ty::{self, Ty, TyCtxt, Instance};
2525
use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt};
2626
use rustc::ty::query::Providers;
27-
use rustc::ty::print::obsolete::DefPathBasedNames;
2827
use rustc::middle::cstore::{self, LinkagePreference};
2928
use rustc::util::common::{time, print_time_passes_entry};
3029
use rustc::session::config::{self, EntryFnType, Lto};
@@ -42,7 +41,6 @@ use crate::callee;
4241
use crate::common::{RealPredicate, TypeKind, IntPredicate};
4342
use crate::meth;
4443
use crate::mir;
45-
use crate::mono_item::MonoItem;
4644

4745
use crate::traits::*;
4846

src/librustc_codegen_ssa/mono_item.rs

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
use rustc::hir;
22
use rustc::mir::mono::{Linkage, Visibility};
33
use rustc::ty::layout::HasTyCtxt;
4-
use std::fmt;
54
use crate::base;
65
use crate::traits::*;
76

8-
pub use rustc::mir::mono::MonoItem;
7+
use rustc::mir::mono::MonoItem;
98

10-
pub use rustc_mir::monomorphize::item::MonoItemExt as BaseMonoItemExt;
9+
pub trait MonoItemExt<'a, 'tcx: 'a> {
10+
fn as_mono_item(&self) -> &MonoItem<'tcx>;
1111

12-
pub trait MonoItemExt<'a, 'tcx: 'a>: fmt::Debug + BaseMonoItemExt<'a, 'tcx> {
1312
fn define<Bx: BuilderMethods<'a, 'tcx>>(&self, cx: &'a Bx::CodegenCx) {
1413
debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
15-
self.to_string(cx.tcx(), true),
16-
self.to_raw_string(),
14+
self.as_mono_item().to_string(cx.tcx(), true),
15+
self.as_mono_item().to_raw_string(),
1716
cx.codegen_unit().name());
1817

1918
match *self.as_mono_item() {
@@ -34,8 +33,8 @@ pub trait MonoItemExt<'a, 'tcx: 'a>: fmt::Debug + BaseMonoItemExt<'a, 'tcx> {
3433
}
3534

3635
debug!("END IMPLEMENTING '{} ({})' in cgu {}",
37-
self.to_string(cx.tcx(), true),
38-
self.to_raw_string(),
36+
self.as_mono_item().to_string(cx.tcx(), true),
37+
self.as_mono_item().to_raw_string(),
3938
cx.codegen_unit().name());
4039
}
4140

@@ -46,11 +45,11 @@ pub trait MonoItemExt<'a, 'tcx: 'a>: fmt::Debug + BaseMonoItemExt<'a, 'tcx> {
4645
visibility: Visibility
4746
) {
4847
debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
49-
self.to_string(cx.tcx(), true),
50-
self.to_raw_string(),
48+
self.as_mono_item().to_string(cx.tcx(), true),
49+
self.as_mono_item().to_raw_string(),
5150
cx.codegen_unit().name());
5251

53-
let symbol_name = self.symbol_name(cx.tcx()).as_str();
52+
let symbol_name = self.as_mono_item().symbol_name(cx.tcx()).as_str();
5453

5554
debug!("symbol {}", &symbol_name);
5655

@@ -65,8 +64,8 @@ pub trait MonoItemExt<'a, 'tcx: 'a>: fmt::Debug + BaseMonoItemExt<'a, 'tcx> {
6564
}
6665

6766
debug!("END PREDEFINING '{} ({})' in cgu {}",
68-
self.to_string(cx.tcx(), true),
69-
self.to_raw_string(),
67+
self.as_mono_item().to_string(cx.tcx(), true),
68+
self.as_mono_item().to_raw_string(),
7069
cx.codegen_unit().name());
7170
}
7271

@@ -87,4 +86,8 @@ pub trait MonoItemExt<'a, 'tcx: 'a>: fmt::Debug + BaseMonoItemExt<'a, 'tcx> {
8786
}
8887
}
8988

90-
impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {}
89+
impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
90+
fn as_mono_item(&self) -> &MonoItem<'tcx> {
91+
self
92+
}
93+
}

src/librustc_codegen_utils/symbol_names.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,7 @@ use rustc::hir::CodegenFnAttrFlags;
9393
use rustc::session::config::SymbolManglingVersion;
9494
use rustc::ty::query::Providers;
9595
use rustc::ty::{self, TyCtxt, Instance};
96-
use rustc::mir::mono::MonoItem;
97-
use rustc_mir::monomorphize::item::{InstantiationMode, MonoItemExt};
96+
use rustc::mir::mono::{MonoItem, InstantiationMode};
9897

9998
use syntax_pos::symbol::InternedString;
10099

src/librustc_mir/monomorphize/collector.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,15 +187,13 @@ use rustc::ty::adjustment::{CustomCoerceUnsized, PointerCast};
187187
use rustc::session::config::EntryFnType;
188188
use rustc::mir::{self, Location, Place, PlaceBase, Promoted, Static, StaticKind};
189189
use rustc::mir::visit::Visitor as MirVisitor;
190-
use rustc::mir::mono::MonoItem;
190+
use rustc::mir::mono::{MonoItem, InstantiationMode};
191191
use rustc::mir::interpret::{Scalar, GlobalId, GlobalAlloc, ErrorHandled};
192192

193193
use crate::monomorphize;
194194
use rustc::util::nodemap::{FxHashSet, FxHashMap, DefIdMap};
195195
use rustc::util::common::time;
196196

197-
use crate::monomorphize::item::{MonoItemExt, InstantiationMode};
198-
199197
use rustc_data_structures::bit_set::GrowableBitSet;
200198
use rustc_data_structures::sync::{MTRef, MTLock, ParallelIterator, par_iter};
201199

src/librustc_mir/monomorphize/mod.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@ use rustc::traits;
22
use rustc::ty::adjustment::CustomCoerceUnsized;
33
use rustc::ty::{self, Ty, TyCtxt};
44

5-
pub use self::item::MonoItemExt;
6-
75
pub mod collector;
8-
pub mod item;
96
pub mod partitioning;
107

118
pub fn custom_coerce_unsize_info<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,

src/librustc_mir/monomorphize/partitioning.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,10 @@ use rustc::ty::print::characteristic_def_id_of_type;
108108
use rustc::ty::query::Providers;
109109
use rustc::util::common::time;
110110
use rustc::util::nodemap::{DefIdSet, FxHashMap, FxHashSet};
111-
use rustc::mir::mono::MonoItem;
111+
use rustc::mir::mono::{MonoItem, InstantiationMode};
112112

113113
use crate::monomorphize::collector::InliningMap;
114114
use crate::monomorphize::collector::{self, MonoItemCollectionMode};
115-
use crate::monomorphize::item::{MonoItemExt, InstantiationMode};
116115

117116
pub enum PartitioningStrategy {
118117
/// Generates one codegen unit per source-level module.

0 commit comments

Comments
 (0)