1 use monomorphize::Instance;
3 use rustc::hir::def_id::DefId;
4 use rustc::session::config::OptLevel;
5 use rustc::ty::{self, Ty, TyCtxt, ClosureSubsts, GeneratorSubsts};
6 use rustc::ty::subst::Substs;
8 use syntax::attr::InlineAttr;
9 use std::fmt::{self, Write};
11 use rustc::mir::mono::Linkage;
12 use syntax_pos::symbol::Symbol;
13 use syntax::source_map::Span;
14 pub use rustc::mir::mono::MonoItem;
16 /// Describes how a monomorphization will be instantiated in object files.
17 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
18 pub enum InstantiationMode {
19 /// There will be exactly one instance of the given MonoItem. It will have
20 /// external linkage so that it can be linked to from other codegen units.
22 /// In some compilation scenarios we may decide to take functions that
23 /// are typically `LocalCopy` and instead move them to `GloballyShared`
24 /// to avoid codegenning them a bunch of times. In this situation,
25 /// however, our local copy may conflict with other crates also
26 /// inlining the same function.
28 /// This flag indicates that this situation is occurring, and informs
29 /// symbol name calculation that some extra mangling is needed to
30 /// avoid conflicts. Note that this may eventually go away entirely if
31 /// ThinLTO enables us to *always* have a globally shared instance of a
32 /// function within one crate's compilation.
36 /// Each codegen unit containing a reference to the given MonoItem will
37 /// have its own private copy of the function (with internal linkage).
41 pub trait MonoItemExt<'a, 'tcx>: fmt::Debug {
42 fn as_mono_item(&self) -> &MonoItem<'tcx>;
44 fn is_generic_fn(&self) -> bool {
45 match *self.as_mono_item() {
46 MonoItem::Fn(ref instance) => {
47 instance.substs.types().next().is_some()
49 MonoItem::Static(..) |
50 MonoItem::GlobalAsm(..) => false,
54 fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
55 match *self.as_mono_item() {
56 MonoItem::Fn(instance) => tcx.symbol_name(instance),
57 MonoItem::Static(def_id) => {
58 tcx.symbol_name(Instance::mono(tcx, def_id))
60 MonoItem::GlobalAsm(node_id) => {
61 let def_id = tcx.hir().local_def_id(node_id);
63 name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_interned_str()
68 fn instantiation_mode(&self,
69 tcx: TyCtxt<'a, 'tcx, 'tcx>)
70 -> InstantiationMode {
71 let inline_in_all_cgus =
72 tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
73 tcx.sess.opts.optimize != OptLevel::No
74 }) && !tcx.sess.opts.cg.link_dead_code;
76 match *self.as_mono_item() {
77 MonoItem::Fn(ref instance) => {
79 tcx.sess.entry_fn.borrow().map(|(id, _, _)| tcx.hir().local_def_id(id));
80 // If this function isn't inlined or otherwise has explicit
81 // linkage, then we'll be creating a globally shared version.
82 if self.explicit_linkage(tcx).is_some() ||
83 !instance.def.requires_local(tcx) ||
84 Some(instance.def_id()) == entry_def_id
86 return InstantiationMode::GloballyShared { may_conflict: false }
89 // At this point we don't have explicit linkage and we're an
90 // inlined function. If we're inlining into all CGUs then we'll
91 // be creating a local copy per CGU
92 if inline_in_all_cgus {
93 return InstantiationMode::LocalCopy
96 // Finally, if this is `#[inline(always)]` we're sure to respect
97 // that with an inline copy per CGU, but otherwise we'll be
98 // creating one copy of this `#[inline]` function which may
99 // conflict with upstream crates as it could be an exported
101 match tcx.codegen_fn_attrs(instance.def_id()).inline {
102 InlineAttr::Always => InstantiationMode::LocalCopy,
104 InstantiationMode::GloballyShared { may_conflict: true }
108 MonoItem::Static(..) |
109 MonoItem::GlobalAsm(..) => {
110 InstantiationMode::GloballyShared { may_conflict: false }
115 fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Linkage> {
116 let def_id = match *self.as_mono_item() {
117 MonoItem::Fn(ref instance) => instance.def_id(),
118 MonoItem::Static(def_id) => def_id,
119 MonoItem::GlobalAsm(..) => return None,
122 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
123 codegen_fn_attrs.linkage
126 /// Returns whether this instance is instantiable - whether it has no unsatisfied
129 /// In order to codegen an item, all of its predicates must hold, because
130 /// otherwise the item does not make sense. Type-checking ensures that
131 /// the predicates of every item that is *used by* a valid item *do*
132 /// hold, so we can rely on that.
134 /// However, we codegen collector roots (reachable items) and functions
135 /// in vtables when they are seen, even if they are not used, and so they
136 /// might not be instantiable. For example, a programmer can define this
139 /// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
140 /// <&mut () as Clone>::clone(&s);
143 /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
144 /// does not exist. Luckily for us, that function can't ever be used,
145 /// because that would require for `&'a mut (): Clone` to hold, so we
146 /// can just not emit any code, or even a linker reference for it.
148 /// Similarly, if a vtable method has such a signature, and therefore can't
149 /// be used, we can just not emit it and have a placeholder (a null pointer,
150 /// which will never be accessed) in its place.
151 fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
152 debug!("is_instantiable({:?})", self);
153 let (def_id, substs) = match *self.as_mono_item() {
154 MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
155 MonoItem::Static(def_id) => (def_id, Substs::empty()),
156 // global asm never has predicates
157 MonoItem::GlobalAsm(..) => return true
160 tcx.substitute_normalize_and_test_predicates((def_id, &substs))
163 fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
164 return match *self.as_mono_item() {
165 MonoItem::Fn(instance) => {
166 to_string_internal(tcx, "fn ", instance)
168 MonoItem::Static(def_id) => {
169 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
170 to_string_internal(tcx, "static ", instance)
172 MonoItem::GlobalAsm(..) => {
173 "global_asm".to_string()
177 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
179 instance: Instance<'tcx>)
181 let mut result = String::with_capacity(32);
182 result.push_str(prefix);
183 let printer = DefPathBasedNames::new(tcx, false, false);
184 printer.push_instance_as_string(instance, &mut result);
189 fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
190 match *self.as_mono_item() {
191 MonoItem::Fn(Instance { def, .. }) => {
192 tcx.hir().as_local_node_id(def.def_id())
194 MonoItem::Static(def_id) => {
195 tcx.hir().as_local_node_id(def_id)
197 MonoItem::GlobalAsm(node_id) => {
200 }.map(|node_id| tcx.hir().span(node_id))
204 impl<'a, 'tcx> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
205 fn as_mono_item(&self) -> &MonoItem<'tcx> {
210 //=-----------------------------------------------------------------------------
211 // MonoItem String Keys
212 //=-----------------------------------------------------------------------------
214 // The code below allows for producing a unique string key for a mono item.
215 // These keys are used by the handwritten auto-tests, so they need to be
216 // predictable and human-readable.
218 // Note: A lot of this could looks very similar to what's already in the
219 // ppaux module. It would be good to refactor things so we only have one
220 // parameterizable implementation for printing types.
222 /// Same as `unique_type_name()` but with the result pushed onto the given
223 /// `output` parameter.
224 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
225 tcx: TyCtxt<'a, 'tcx, 'tcx>,
226 omit_disambiguators: bool,
227 omit_local_crate_name: bool,
230 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
231 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
232 omit_disambiguators: bool,
233 omit_local_crate_name: bool)
238 omit_local_crate_name,
242 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
244 ty::Bool => output.push_str("bool"),
245 ty::Char => output.push_str("char"),
246 ty::Str => output.push_str("str"),
247 ty::Never => output.push_str("!"),
248 ty::Int(ast::IntTy::Isize) => output.push_str("isize"),
249 ty::Int(ast::IntTy::I8) => output.push_str("i8"),
250 ty::Int(ast::IntTy::I16) => output.push_str("i16"),
251 ty::Int(ast::IntTy::I32) => output.push_str("i32"),
252 ty::Int(ast::IntTy::I64) => output.push_str("i64"),
253 ty::Int(ast::IntTy::I128) => output.push_str("i128"),
254 ty::Uint(ast::UintTy::Usize) => output.push_str("usize"),
255 ty::Uint(ast::UintTy::U8) => output.push_str("u8"),
256 ty::Uint(ast::UintTy::U16) => output.push_str("u16"),
257 ty::Uint(ast::UintTy::U32) => output.push_str("u32"),
258 ty::Uint(ast::UintTy::U64) => output.push_str("u64"),
259 ty::Uint(ast::UintTy::U128) => output.push_str("u128"),
260 ty::Float(ast::FloatTy::F32) => output.push_str("f32"),
261 ty::Float(ast::FloatTy::F64) => output.push_str("f64"),
262 ty::Adt(adt_def, substs) => {
263 self.push_def_path(adt_def.did, output);
264 self.push_type_params(substs, iter::empty(), output);
266 ty::Tuple(component_types) => {
268 for &component_type in component_types {
269 self.push_type_name(component_type, output);
270 output.push_str(", ");
272 if !component_types.is_empty() {
278 ty::RawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
281 hir::MutImmutable => output.push_str("const "),
282 hir::MutMutable => output.push_str("mut "),
285 self.push_type_name(inner_type, output);
287 ty::Ref(_, inner_type, mutbl) => {
289 if mutbl == hir::MutMutable {
290 output.push_str("mut ");
293 self.push_type_name(inner_type, output);
295 ty::Array(inner_type, len) => {
297 self.push_type_name(inner_type, output);
298 write!(output, "; {}", len.unwrap_usize(self.tcx)).unwrap();
301 ty::Slice(inner_type) => {
303 self.push_type_name(inner_type, output);
306 ty::Dynamic(ref trait_data, ..) => {
307 if let Some(principal) = trait_data.principal() {
308 self.push_def_path(principal.def_id(), output);
309 self.push_type_params(
310 principal.skip_binder().substs,
311 trait_data.projection_bounds(),
315 output.push_str("dyn '_");
318 ty::Foreign(did) => self.push_def_path(did, output),
321 let sig = t.fn_sig(self.tcx);
322 if sig.unsafety() == hir::Unsafety::Unsafe {
323 output.push_str("unsafe ");
327 if abi != ::rustc_target::spec::abi::Abi::Rust {
328 output.push_str("extern \"");
329 output.push_str(abi.name());
330 output.push_str("\" ");
333 output.push_str("fn(");
335 let sig = self.tcx.normalize_erasing_late_bound_regions(
336 ty::ParamEnv::reveal_all(),
340 if !sig.inputs().is_empty() {
341 for ¶meter_type in sig.inputs() {
342 self.push_type_name(parameter_type, output);
343 output.push_str(", ");
350 if !sig.inputs().is_empty() {
351 output.push_str(", ...");
353 output.push_str("...");
359 if !sig.output().is_unit() {
360 output.push_str(" -> ");
361 self.push_type_name(sig.output(), output);
364 ty::Generator(def_id, GeneratorSubsts { ref substs }, _) |
365 ty::Closure(def_id, ClosureSubsts { ref substs }) => {
366 self.push_def_path(def_id, output);
367 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
368 let substs = substs.truncate_to(self.tcx, generics);
369 self.push_type_params(substs, iter::empty(), output);
374 ty::Placeholder(..) |
375 ty::UnnormalizedProjection(..) |
378 ty::GeneratorWitness(_) |
380 bug!("DefPathBasedNames: Trying to create type name for \
381 unexpected type: {:?}", t);
386 pub fn push_def_path(&self,
388 output: &mut String) {
389 let def_path = self.tcx.def_path(def_id);
392 if !(self.omit_local_crate_name && def_id.is_local()) {
393 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
394 output.push_str("::");
397 // foo::bar::ItemName::
398 for part in self.tcx.def_path(def_id).data {
399 if self.omit_disambiguators {
400 write!(output, "{}::", part.data.as_interned_str()).unwrap();
402 write!(output, "{}[{}]::",
403 part.data.as_interned_str(),
404 part.disambiguator).unwrap();
413 fn push_type_params<I>(&self,
414 substs: &Substs<'tcx>,
417 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
419 let mut projections = projections.peekable();
420 if substs.types().next().is_none() && projections.peek().is_none() {
426 for type_parameter in substs.types() {
427 self.push_type_name(type_parameter, output);
428 output.push_str(", ");
431 for projection in projections {
432 let projection = projection.skip_binder();
433 let name = &self.tcx.associated_item(projection.item_def_id).ident.as_str();
434 output.push_str(name);
435 output.push_str("=");
436 self.push_type_name(projection.ty, output);
437 output.push_str(", ");
446 pub fn push_instance_as_string(&self,
447 instance: Instance<'tcx>,
448 output: &mut String) {
449 self.push_def_path(instance.def_id(), output);
450 self.push_type_params(instance.substs, iter::empty(), output);