]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/instance.rs
fix most compiler/ doctests
[rust.git] / compiler / rustc_middle / src / ty / instance.rs
1 use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
2 use crate::ty::print::{FmtPrinter, Printer};
3 use crate::ty::subst::{InternalSubsts, Subst};
4 use crate::ty::{self, SubstsRef, Ty, TyCtxt, TypeFoldable};
5 use rustc_errors::ErrorGuaranteed;
6 use rustc_hir::def::Namespace;
7 use rustc_hir::def_id::{CrateNum, DefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_macros::HashStable;
10 use rustc_middle::ty::normalize_erasing_regions::NormalizationError;
11
12 use std::fmt;
13
14 /// A monomorphized `InstanceDef`.
15 ///
16 /// Monomorphization happens on-the-fly and no monomorphized MIR is ever created. Instead, this type
17 /// simply couples a potentially generic `InstanceDef` with some substs, and codegen and const eval
18 /// will do all required substitution as they run.
19 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
20 #[derive(HashStable, Lift)]
21 pub struct Instance<'tcx> {
22     pub def: InstanceDef<'tcx>,
23     pub substs: SubstsRef<'tcx>,
24 }
25
26 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
27 #[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable)]
28 pub enum InstanceDef<'tcx> {
29     /// A user-defined callable item.
30     ///
31     /// This includes:
32     /// - `fn` items
33     /// - closures
34     /// - generators
35     Item(ty::WithOptConstParam<DefId>),
36
37     /// An intrinsic `fn` item (with `"rust-intrinsic"` or `"platform-intrinsic"` ABI).
38     ///
39     /// Alongside `Virtual`, this is the only `InstanceDef` that does not have its own callable MIR.
40     /// Instead, codegen and const eval "magically" evaluate calls to intrinsics purely in the
41     /// caller.
42     Intrinsic(DefId),
43
44     /// `<T as Trait>::method` where `method` receives unsizeable `self: Self` (part of the
45     /// `unsized_locals` feature).
46     ///
47     /// The generated shim will take `Self` via `*mut Self` - conceptually this is `&owned Self` -
48     /// and dereference the argument to call the original function.
49     VtableShim(DefId),
50
51     /// `fn()` pointer where the function itself cannot be turned into a pointer.
52     ///
53     /// One example is `<dyn Trait as Trait>::fn`, where the shim contains
54     /// a virtual call, which codegen supports only via a direct call to the
55     /// `<dyn Trait as Trait>::fn` instance (an `InstanceDef::Virtual`).
56     ///
57     /// Another example is functions annotated with `#[track_caller]`, which
58     /// must have their implicit caller location argument populated for a call.
59     /// Because this is a required part of the function's ABI but can't be tracked
60     /// as a property of the function pointer, we use a single "caller location"
61     /// (the definition of the function itself).
62     ReifyShim(DefId),
63
64     /// `<fn() as FnTrait>::call_*` (generated `FnTrait` implementation for `fn()` pointers).
65     ///
66     /// `DefId` is `FnTrait::call_*`.
67     FnPtrShim(DefId, Ty<'tcx>),
68
69     /// Dynamic dispatch to `<dyn Trait as Trait>::fn`.
70     ///
71     /// This `InstanceDef` does not have callable MIR. Calls to `Virtual` instances must be
72     /// codegen'd as virtual calls through the vtable.
73     ///
74     /// If this is reified to a `fn` pointer, a `ReifyShim` is used (see `ReifyShim` above for more
75     /// details on that).
76     Virtual(DefId, usize),
77
78     /// `<[FnMut closure] as FnOnce>::call_once`.
79     ///
80     /// The `DefId` is the ID of the `call_once` method in `FnOnce`.
81     ClosureOnceShim { call_once: DefId, track_caller: bool },
82
83     /// `core::ptr::drop_in_place::<T>`.
84     ///
85     /// The `DefId` is for `core::ptr::drop_in_place`.
86     /// The `Option<Ty<'tcx>>` is either `Some(T)`, or `None` for empty drop
87     /// glue.
88     DropGlue(DefId, Option<Ty<'tcx>>),
89
90     /// Compiler-generated `<T as Clone>::clone` implementation.
91     ///
92     /// For all types that automatically implement `Copy`, a trivial `Clone` impl is provided too.
93     /// Additionally, arrays, tuples, and closures get a `Clone` shim even if they aren't `Copy`.
94     ///
95     /// The `DefId` is for `Clone::clone`, the `Ty` is the type `T` with the builtin `Clone` impl.
96     CloneShim(DefId, Ty<'tcx>),
97 }
98
99 impl<'tcx> Instance<'tcx> {
100     /// Returns the `Ty` corresponding to this `Instance`, with generic substitutions applied and
101     /// lifetimes erased, allowing a `ParamEnv` to be specified for use during normalization.
102     pub fn ty(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Ty<'tcx> {
103         let ty = tcx.type_of(self.def.def_id());
104         tcx.subst_and_normalize_erasing_regions(self.substs, param_env, ty)
105     }
106
107     /// Finds a crate that contains a monomorphization of this instance that
108     /// can be linked to from the local crate. A return value of `None` means
109     /// no upstream crate provides such an exported monomorphization.
110     ///
111     /// This method already takes into account the global `-Zshare-generics`
112     /// setting, always returning `None` if `share-generics` is off.
113     pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum> {
114         // If we are not in share generics mode, we don't link to upstream
115         // monomorphizations but always instantiate our own internal versions
116         // instead.
117         if !tcx.sess.opts.share_generics() {
118             return None;
119         }
120
121         // If this is an item that is defined in the local crate, no upstream
122         // crate can know about it/provide a monomorphization.
123         if self.def_id().is_local() {
124             return None;
125         }
126
127         // If this a non-generic instance, it cannot be a shared monomorphization.
128         self.substs.non_erasable_generics().next()?;
129
130         match self.def {
131             InstanceDef::Item(def) => tcx
132                 .upstream_monomorphizations_for(def.did)
133                 .and_then(|monos| monos.get(&self.substs).cloned()),
134             InstanceDef::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.substs),
135             _ => None,
136         }
137     }
138 }
139
140 impl<'tcx> InstanceDef<'tcx> {
141     #[inline]
142     pub fn def_id(self) -> DefId {
143         match self {
144             InstanceDef::Item(def) => def.did,
145             InstanceDef::VtableShim(def_id)
146             | InstanceDef::ReifyShim(def_id)
147             | InstanceDef::FnPtrShim(def_id, _)
148             | InstanceDef::Virtual(def_id, _)
149             | InstanceDef::Intrinsic(def_id)
150             | InstanceDef::ClosureOnceShim { call_once: def_id, track_caller: _ }
151             | InstanceDef::DropGlue(def_id, _)
152             | InstanceDef::CloneShim(def_id, _) => def_id,
153         }
154     }
155
156     /// Returns the `DefId` of instances which might not require codegen locally.
157     pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId> {
158         match self {
159             ty::InstanceDef::Item(def) => Some(def.did),
160             ty::InstanceDef::DropGlue(def_id, Some(_)) => Some(def_id),
161             InstanceDef::VtableShim(..)
162             | InstanceDef::ReifyShim(..)
163             | InstanceDef::FnPtrShim(..)
164             | InstanceDef::Virtual(..)
165             | InstanceDef::Intrinsic(..)
166             | InstanceDef::ClosureOnceShim { .. }
167             | InstanceDef::DropGlue(..)
168             | InstanceDef::CloneShim(..) => None,
169         }
170     }
171
172     #[inline]
173     pub fn with_opt_param(self) -> ty::WithOptConstParam<DefId> {
174         match self {
175             InstanceDef::Item(def) => def,
176             InstanceDef::VtableShim(def_id)
177             | InstanceDef::ReifyShim(def_id)
178             | InstanceDef::FnPtrShim(def_id, _)
179             | InstanceDef::Virtual(def_id, _)
180             | InstanceDef::Intrinsic(def_id)
181             | InstanceDef::ClosureOnceShim { call_once: def_id, track_caller: _ }
182             | InstanceDef::DropGlue(def_id, _)
183             | InstanceDef::CloneShim(def_id, _) => ty::WithOptConstParam::unknown(def_id),
184         }
185     }
186
187     #[inline]
188     pub fn attrs(&self, tcx: TyCtxt<'tcx>) -> ty::Attributes<'tcx> {
189         tcx.get_attrs(self.def_id())
190     }
191
192     /// Returns `true` if the LLVM version of this instance is unconditionally
193     /// marked with `inline`. This implies that a copy of this instance is
194     /// generated in every codegen unit.
195     /// Note that this is only a hint. See the documentation for
196     /// `generates_cgu_internal_copy` for more information.
197     pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
198         use rustc_hir::definitions::DefPathData;
199         let def_id = match *self {
200             ty::InstanceDef::Item(def) => def.did,
201             ty::InstanceDef::DropGlue(_, Some(_)) => return false,
202             _ => return true,
203         };
204         matches!(
205             tcx.def_key(def_id).disambiguated_data.data,
206             DefPathData::Ctor | DefPathData::ClosureExpr
207         )
208     }
209
210     /// Returns `true` if the machine code for this instance is instantiated in
211     /// each codegen unit that references it.
212     /// Note that this is only a hint! The compiler can globally decide to *not*
213     /// do this in order to speed up compilation. CGU-internal copies are
214     /// only exist to enable inlining. If inlining is not performed (e.g. at
215     /// `-Copt-level=0`) then the time for generating them is wasted and it's
216     /// better to create a single copy with external linkage.
217     pub fn generates_cgu_internal_copy(&self, tcx: TyCtxt<'tcx>) -> bool {
218         if self.requires_inline(tcx) {
219             return true;
220         }
221         if let ty::InstanceDef::DropGlue(.., Some(ty)) = *self {
222             // Drop glue generally wants to be instantiated at every codegen
223             // unit, but without an #[inline] hint. We should make this
224             // available to normal end-users.
225             if tcx.sess.opts.incremental.is_none() {
226                 return true;
227             }
228             // When compiling with incremental, we can generate a *lot* of
229             // codegen units. Including drop glue into all of them has a
230             // considerable compile time cost.
231             //
232             // We include enums without destructors to allow, say, optimizing
233             // drops of `Option::None` before LTO. We also respect the intent of
234             // `#[inline]` on `Drop::drop` implementations.
235             return ty.ty_adt_def().map_or(true, |adt_def| {
236                 adt_def.destructor(tcx).map_or_else(
237                     || adt_def.is_enum(),
238                     |dtor| tcx.codegen_fn_attrs(dtor.did).requests_inline(),
239                 )
240             });
241         }
242         tcx.codegen_fn_attrs(self.def_id()).requests_inline()
243     }
244
245     pub fn requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool {
246         match *self {
247             InstanceDef::Item(ty::WithOptConstParam { did: def_id, .. })
248             | InstanceDef::Virtual(def_id, _) => {
249                 tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
250             }
251             InstanceDef::ClosureOnceShim { call_once: _, track_caller } => track_caller,
252             _ => false,
253         }
254     }
255
256     /// Returns `true` when the MIR body associated with this instance should be monomorphized
257     /// by its users (e.g. codegen or miri) by substituting the `substs` from `Instance` (see
258     /// `Instance::substs_for_mir_body`).
259     ///
260     /// Otherwise, returns `false` only for some kinds of shims where the construction of the MIR
261     /// body should perform necessary substitutions.
262     pub fn has_polymorphic_mir_body(&self) -> bool {
263         match *self {
264             InstanceDef::CloneShim(..)
265             | InstanceDef::FnPtrShim(..)
266             | InstanceDef::DropGlue(_, Some(_)) => false,
267             InstanceDef::ClosureOnceShim { .. }
268             | InstanceDef::DropGlue(..)
269             | InstanceDef::Item(_)
270             | InstanceDef::Intrinsic(..)
271             | InstanceDef::ReifyShim(..)
272             | InstanceDef::Virtual(..)
273             | InstanceDef::VtableShim(..) => true,
274         }
275     }
276 }
277
278 impl<'tcx> fmt::Display for Instance<'tcx> {
279     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280         ty::tls::with(|tcx| {
281             let substs = tcx.lift(self.substs).expect("could not lift for printing");
282             let s = FmtPrinter::new(tcx, Namespace::ValueNS)
283                 .print_def_path(self.def_id(), substs)?
284                 .into_buffer();
285             f.write_str(&s)
286         })?;
287
288         match self.def {
289             InstanceDef::Item(_) => Ok(()),
290             InstanceDef::VtableShim(_) => write!(f, " - shim(vtable)"),
291             InstanceDef::ReifyShim(_) => write!(f, " - shim(reify)"),
292             InstanceDef::Intrinsic(_) => write!(f, " - intrinsic"),
293             InstanceDef::Virtual(_, num) => write!(f, " - virtual#{}", num),
294             InstanceDef::FnPtrShim(_, ty) => write!(f, " - shim({})", ty),
295             InstanceDef::ClosureOnceShim { .. } => write!(f, " - shim"),
296             InstanceDef::DropGlue(_, None) => write!(f, " - shim(None)"),
297             InstanceDef::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({}))", ty),
298             InstanceDef::CloneShim(_, ty) => write!(f, " - shim({})", ty),
299         }
300     }
301 }
302
303 impl<'tcx> Instance<'tcx> {
304     pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> Instance<'tcx> {
305         assert!(
306             !substs.has_escaping_bound_vars(),
307             "substs of instance {:?} not normalized for codegen: {:?}",
308             def_id,
309             substs
310         );
311         Instance { def: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)), substs }
312     }
313
314     pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> {
315         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
316             ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
317             ty::GenericParamDefKind::Type { .. } => {
318                 bug!("Instance::mono: {:?} has type parameters", def_id)
319             }
320             ty::GenericParamDefKind::Const { .. } => {
321                 bug!("Instance::mono: {:?} has const parameters", def_id)
322             }
323         });
324
325         Instance::new(def_id, substs)
326     }
327
328     #[inline]
329     pub fn def_id(&self) -> DefId {
330         self.def.def_id()
331     }
332
333     /// Resolves a `(def_id, substs)` pair to an (optional) instance -- most commonly,
334     /// this is used to find the precise code that will run for a trait method invocation,
335     /// if known.
336     ///
337     /// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance.
338     /// For example, in a context like this,
339     ///
340     /// ```ignore (illustrative)
341     /// fn foo<T: Debug>(t: T) { ... }
342     /// ```
343     ///
344     /// trying to resolve `Debug::fmt` applied to `T` will yield `Ok(None)`, because we do not
345     /// know what code ought to run. (Note that this setting is also affected by the
346     /// `RevealMode` in the parameter environment.)
347     ///
348     /// Presuming that coherence and type-check have succeeded, if this method is invoked
349     /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
350     /// `Ok(Some(instance))`.
351     ///
352     /// Returns `Err(ErrorGuaranteed)` when the `Instance` resolution process
353     /// couldn't complete due to errors elsewhere - this is distinct
354     /// from `Ok(None)` to avoid misleading diagnostics when an error
355     /// has already been/will be emitted, for the original cause
356     pub fn resolve(
357         tcx: TyCtxt<'tcx>,
358         param_env: ty::ParamEnv<'tcx>,
359         def_id: DefId,
360         substs: SubstsRef<'tcx>,
361     ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
362         Instance::resolve_opt_const_arg(
363             tcx,
364             param_env,
365             ty::WithOptConstParam::unknown(def_id),
366             substs,
367         )
368     }
369
370     // This should be kept up to date with `resolve`.
371     #[instrument(level = "debug", skip(tcx))]
372     pub fn resolve_opt_const_arg(
373         tcx: TyCtxt<'tcx>,
374         param_env: ty::ParamEnv<'tcx>,
375         def: ty::WithOptConstParam<DefId>,
376         substs: SubstsRef<'tcx>,
377     ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
378         // All regions in the result of this query are erased, so it's
379         // fine to erase all of the input regions.
380
381         // HACK(eddyb) erase regions in `substs` first, so that `param_env.and(...)`
382         // below is more likely to ignore the bounds in scope (e.g. if the only
383         // generic parameters mentioned by `substs` were lifetime ones).
384         let substs = tcx.erase_regions(substs);
385
386         // FIXME(eddyb) should this always use `param_env.with_reveal_all()`?
387         if let Some((did, param_did)) = def.as_const_arg() {
388             tcx.resolve_instance_of_const_arg(
389                 tcx.erase_regions(param_env.and((did, param_did, substs))),
390             )
391         } else {
392             tcx.resolve_instance(tcx.erase_regions(param_env.and((def.did, substs))))
393         }
394     }
395
396     pub fn resolve_for_fn_ptr(
397         tcx: TyCtxt<'tcx>,
398         param_env: ty::ParamEnv<'tcx>,
399         def_id: DefId,
400         substs: SubstsRef<'tcx>,
401     ) -> Option<Instance<'tcx>> {
402         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
403         // Use either `resolve_closure` or `resolve_for_vtable`
404         assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {:?}", def_id);
405         Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| {
406             match resolved.def {
407                 InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => {
408                     debug!(" => fn pointer created for function with #[track_caller]");
409                     resolved.def = InstanceDef::ReifyShim(def.did);
410                 }
411                 InstanceDef::Virtual(def_id, _) => {
412                     debug!(" => fn pointer created for virtual call");
413                     resolved.def = InstanceDef::ReifyShim(def_id);
414                 }
415                 _ => {}
416             }
417
418             resolved
419         })
420     }
421
422     pub fn resolve_for_vtable(
423         tcx: TyCtxt<'tcx>,
424         param_env: ty::ParamEnv<'tcx>,
425         def_id: DefId,
426         substs: SubstsRef<'tcx>,
427     ) -> Option<Instance<'tcx>> {
428         debug!("resolve_for_vtable(def_id={:?}, substs={:?})", def_id, substs);
429         let fn_sig = tcx.fn_sig(def_id);
430         let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty()
431             && fn_sig.input(0).skip_binder().is_param(0)
432             && tcx.generics_of(def_id).has_self;
433         if is_vtable_shim {
434             debug!(" => associated item with unsizeable self: Self");
435             Some(Instance { def: InstanceDef::VtableShim(def_id), substs })
436         } else {
437             Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| {
438                 match resolved.def {
439                     InstanceDef::Item(def) => {
440                         // We need to generate a shim when we cannot guarantee that
441                         // the caller of a trait object method will be aware of
442                         // `#[track_caller]` - this ensures that the caller
443                         // and callee ABI will always match.
444                         //
445                         // The shim is generated when all of these conditions are met:
446                         //
447                         // 1) The underlying method expects a caller location parameter
448                         // in the ABI
449                         if resolved.def.requires_caller_location(tcx)
450                             // 2) The caller location parameter comes from having `#[track_caller]`
451                             // on the implementation, and *not* on the trait method.
452                             && !tcx.should_inherit_track_caller(def.did)
453                             // If the method implementation comes from the trait definition itself
454                             // (e.g. `trait Foo { #[track_caller] my_fn() { /* impl */ } }`),
455                             // then we don't need to generate a shim. This check is needed because
456                             // `should_inherit_track_caller` returns `false` if our method
457                             // implementation comes from the trait block, and not an impl block
458                             && !matches!(
459                                 tcx.opt_associated_item(def.did),
460                                 Some(ty::AssocItem {
461                                     container: ty::AssocItemContainer::TraitContainer(_),
462                                     ..
463                                 })
464                             )
465                         {
466                             if tcx.is_closure(def.did) {
467                                 debug!(" => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}",
468                                        def.did, def_id, substs);
469
470                                 // Create a shim for the `FnOnce/FnMut/Fn` method we are calling
471                                 // - unlike functions, invoking a closure always goes through a
472                                 // trait.
473                                 resolved = Instance { def: InstanceDef::ReifyShim(def_id), substs };
474                             } else {
475                                 debug!(
476                                     " => vtable fn pointer created for function with #[track_caller]: {:?}", def.did
477                                 );
478                                 resolved.def = InstanceDef::ReifyShim(def.did);
479                             }
480                         }
481                     }
482                     InstanceDef::Virtual(def_id, _) => {
483                         debug!(" => vtable fn pointer created for virtual call");
484                         resolved.def = InstanceDef::ReifyShim(def_id);
485                     }
486                     _ => {}
487                 }
488
489                 resolved
490             })
491         }
492     }
493
494     pub fn resolve_closure(
495         tcx: TyCtxt<'tcx>,
496         def_id: DefId,
497         substs: ty::SubstsRef<'tcx>,
498         requested_kind: ty::ClosureKind,
499     ) -> Instance<'tcx> {
500         let actual_kind = substs.as_closure().kind();
501
502         match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
503             Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs),
504             _ => Instance::new(def_id, substs),
505         }
506     }
507
508     pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
509         let def_id = tcx.require_lang_item(LangItem::DropInPlace, None);
510         let substs = tcx.intern_substs(&[ty.into()]);
511         Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap().unwrap()
512     }
513
514     pub fn fn_once_adapter_instance(
515         tcx: TyCtxt<'tcx>,
516         closure_did: DefId,
517         substs: ty::SubstsRef<'tcx>,
518     ) -> Instance<'tcx> {
519         debug!("fn_once_adapter_shim({:?}, {:?})", closure_did, substs);
520         let fn_once = tcx.require_lang_item(LangItem::FnOnce, None);
521         let call_once = tcx
522             .associated_items(fn_once)
523             .in_definition_order()
524             .find(|it| it.kind == ty::AssocKind::Fn)
525             .unwrap()
526             .def_id;
527         let track_caller =
528             tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER);
529         let def = ty::InstanceDef::ClosureOnceShim { call_once, track_caller };
530
531         let self_ty = tcx.mk_closure(closure_did, substs);
532
533         let sig = substs.as_closure().sig();
534         let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig);
535         assert_eq!(sig.inputs().len(), 1);
536         let substs = tcx.mk_substs_trait(self_ty, &[sig.inputs()[0].into()]);
537
538         debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
539         Instance { def, substs }
540     }
541
542     /// Depending on the kind of `InstanceDef`, the MIR body associated with an
543     /// instance is expressed in terms of the generic parameters of `self.def_id()`, and in other
544     /// cases the MIR body is expressed in terms of the types found in the substitution array.
545     /// In the former case, we want to substitute those generic types and replace them with the
546     /// values from the substs when monomorphizing the function body. But in the latter case, we
547     /// don't want to do that substitution, since it has already been done effectively.
548     ///
549     /// This function returns `Some(substs)` in the former case and `None` otherwise -- i.e., if
550     /// this function returns `None`, then the MIR body does not require substitution during
551     /// codegen.
552     fn substs_for_mir_body(&self) -> Option<SubstsRef<'tcx>> {
553         if self.def.has_polymorphic_mir_body() { Some(self.substs) } else { None }
554     }
555
556     pub fn subst_mir<T>(&self, tcx: TyCtxt<'tcx>, v: &T) -> T
557     where
558         T: TypeFoldable<'tcx> + Copy,
559     {
560         if let Some(substs) = self.substs_for_mir_body() { v.subst(tcx, substs) } else { *v }
561     }
562
563     #[inline(always)]
564     pub fn subst_mir_and_normalize_erasing_regions<T>(
565         &self,
566         tcx: TyCtxt<'tcx>,
567         param_env: ty::ParamEnv<'tcx>,
568         v: T,
569     ) -> T
570     where
571         T: TypeFoldable<'tcx> + Clone,
572     {
573         if let Some(substs) = self.substs_for_mir_body() {
574             tcx.subst_and_normalize_erasing_regions(substs, param_env, v)
575         } else {
576             tcx.normalize_erasing_regions(param_env, v)
577         }
578     }
579
580     #[inline(always)]
581     pub fn try_subst_mir_and_normalize_erasing_regions<T>(
582         &self,
583         tcx: TyCtxt<'tcx>,
584         param_env: ty::ParamEnv<'tcx>,
585         v: T,
586     ) -> Result<T, NormalizationError<'tcx>>
587     where
588         T: TypeFoldable<'tcx> + Clone,
589     {
590         if let Some(substs) = self.substs_for_mir_body() {
591             tcx.try_subst_and_normalize_erasing_regions(substs, param_env, v)
592         } else {
593             tcx.try_normalize_erasing_regions(param_env, v)
594         }
595     }
596
597     /// Returns a new `Instance` where generic parameters in `instance.substs` are replaced by
598     /// identity parameters if they are determined to be unused in `instance.def`.
599     pub fn polymorphize(self, tcx: TyCtxt<'tcx>) -> Self {
600         debug!("polymorphize: running polymorphization analysis");
601         if !tcx.sess.opts.debugging_opts.polymorphize {
602             return self;
603         }
604
605         let polymorphized_substs = polymorphize(tcx, self.def, self.substs);
606         debug!("polymorphize: self={:?} polymorphized_substs={:?}", self, polymorphized_substs);
607         Self { def: self.def, substs: polymorphized_substs }
608     }
609 }
610
611 fn polymorphize<'tcx>(
612     tcx: TyCtxt<'tcx>,
613     instance: ty::InstanceDef<'tcx>,
614     substs: SubstsRef<'tcx>,
615 ) -> SubstsRef<'tcx> {
616     debug!("polymorphize({:?}, {:?})", instance, substs);
617     let unused = tcx.unused_generic_params(instance);
618     debug!("polymorphize: unused={:?}", unused);
619
620     // If this is a closure or generator then we need to handle the case where another closure
621     // from the function is captured as an upvar and hasn't been polymorphized. In this case,
622     // the unpolymorphized upvar closure would result in a polymorphized closure producing
623     // multiple mono items (and eventually symbol clashes).
624     let def_id = instance.def_id();
625     let upvars_ty = if tcx.is_closure(def_id) {
626         Some(substs.as_closure().tupled_upvars_ty())
627     } else if tcx.type_of(def_id).is_generator() {
628         Some(substs.as_generator().tupled_upvars_ty())
629     } else {
630         None
631     };
632     let has_upvars = upvars_ty.map_or(false, |ty| !ty.tuple_fields().is_empty());
633     debug!("polymorphize: upvars_ty={:?} has_upvars={:?}", upvars_ty, has_upvars);
634
635     struct PolymorphizationFolder<'tcx> {
636         tcx: TyCtxt<'tcx>,
637     }
638
639     impl<'tcx> ty::TypeFolder<'tcx> for PolymorphizationFolder<'tcx> {
640         fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
641             self.tcx
642         }
643
644         fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
645             debug!("fold_ty: ty={:?}", ty);
646             match *ty.kind() {
647                 ty::Closure(def_id, substs) => {
648                     let polymorphized_substs = polymorphize(
649                         self.tcx,
650                         ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
651                         substs,
652                     );
653                     if substs == polymorphized_substs {
654                         ty
655                     } else {
656                         self.tcx.mk_closure(def_id, polymorphized_substs)
657                     }
658                 }
659                 ty::Generator(def_id, substs, movability) => {
660                     let polymorphized_substs = polymorphize(
661                         self.tcx,
662                         ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)),
663                         substs,
664                     );
665                     if substs == polymorphized_substs {
666                         ty
667                     } else {
668                         self.tcx.mk_generator(def_id, polymorphized_substs, movability)
669                     }
670                 }
671                 _ => ty.super_fold_with(self),
672             }
673         }
674     }
675
676     InternalSubsts::for_item(tcx, def_id, |param, _| {
677         let is_unused = unused.contains(param.index).unwrap_or(false);
678         debug!("polymorphize: param={:?} is_unused={:?}", param, is_unused);
679         match param.kind {
680             // Upvar case: If parameter is a type parameter..
681             ty::GenericParamDefKind::Type { .. } if
682                 // ..and has upvars..
683                 has_upvars &&
684                 // ..and this param has the same type as the tupled upvars..
685                 upvars_ty == Some(substs[param.index as usize].expect_ty()) => {
686                     // ..then double-check that polymorphization marked it used..
687                     debug_assert!(!is_unused);
688                     // ..and polymorphize any closures/generators captured as upvars.
689                     let upvars_ty = upvars_ty.unwrap();
690                     let polymorphized_upvars_ty = upvars_ty.fold_with(
691                         &mut PolymorphizationFolder { tcx });
692                     debug!("polymorphize: polymorphized_upvars_ty={:?}", polymorphized_upvars_ty);
693                     ty::GenericArg::from(polymorphized_upvars_ty)
694                 },
695
696             // Simple case: If parameter is a const or type parameter..
697             ty::GenericParamDefKind::Const { .. } | ty::GenericParamDefKind::Type { .. } if
698                 // ..and is within range and unused..
699                 unused.contains(param.index).unwrap_or(false) =>
700                     // ..then use the identity for this parameter.
701                     tcx.mk_param_from_def(param),
702
703             // Otherwise, use the parameter as before.
704             _ => substs[param.index as usize],
705         }
706     })
707 }
708
709 fn needs_fn_once_adapter_shim(
710     actual_closure_kind: ty::ClosureKind,
711     trait_closure_kind: ty::ClosureKind,
712 ) -> Result<bool, ()> {
713     match (actual_closure_kind, trait_closure_kind) {
714         (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
715         | (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut)
716         | (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
717             // No adapter needed.
718             Ok(false)
719         }
720         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
721             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
722             // `fn(&mut self, ...)`. In fact, at codegen time, these are
723             // basically the same thing, so we can just return llfn.
724             Ok(false)
725         }
726         (ty::ClosureKind::Fn | ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
727             // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
728             // self, ...)`.  We want a `fn(self, ...)`. We can produce
729             // this by doing something like:
730             //
731             //     fn call_once(self, ...) { call_mut(&self, ...) }
732             //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
733             //
734             // These are both the same at codegen time.
735             Ok(true)
736         }
737         (ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce, _) => Err(()),
738     }
739 }