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