]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/instance.rs
Update ub-uninhabit tests
[rust.git] / src / librustc / ty / instance.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use hir::Unsafety;
12 use hir::def_id::DefId;
13 use ty::{self, Ty, PolyFnSig, TypeFoldable, Substs, TyCtxt};
14 use traits;
15 use rustc_target::spec::abi::Abi;
16 use util::ppaux;
17
18 use std::fmt;
19 use std::iter;
20
21 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
22 pub struct Instance<'tcx> {
23     pub def: InstanceDef<'tcx>,
24     pub substs: &'tcx Substs<'tcx>,
25 }
26
27 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
28 pub enum InstanceDef<'tcx> {
29     Item(DefId),
30     Intrinsic(DefId),
31
32     /// `<T as Trait>::method` where `method` receives unsizeable `self: Self`.
33     VtableShim(DefId),
34
35     /// \<fn() as FnTrait>::call_*
36     /// def-id is FnTrait::call_*
37     FnPtrShim(DefId, Ty<'tcx>),
38
39     /// <Trait as Trait>::fn
40     Virtual(DefId, usize),
41
42     /// <[mut closure] as FnOnce>::call_once
43     ClosureOnceShim { call_once: DefId },
44
45     /// drop_in_place::<T>; None for empty drop glue.
46     DropGlue(DefId, Option<Ty<'tcx>>),
47
48     ///`<T as Clone>::clone` shim.
49     CloneShim(DefId, Ty<'tcx>),
50 }
51
52 impl<'a, 'tcx> Instance<'tcx> {
53     pub fn ty(&self,
54               tcx: TyCtxt<'a, 'tcx, 'tcx>)
55               -> Ty<'tcx>
56     {
57         let ty = tcx.type_of(self.def.def_id());
58         tcx.subst_and_normalize_erasing_regions(
59             self.substs,
60             ty::ParamEnv::reveal_all(),
61             &ty,
62         )
63     }
64
65     fn fn_sig_noadjust(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> PolyFnSig<'tcx> {
66         let ty = self.ty(tcx);
67         match ty.sty {
68             ty::FnDef(..) |
69             // Shims currently have type FnPtr. Not sure this should remain.
70             ty::FnPtr(_) => ty.fn_sig(tcx),
71             ty::Closure(def_id, substs) => {
72                 let sig = substs.closure_sig(def_id, tcx);
73
74                 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
75                 sig.map_bound(|sig| tcx.mk_fn_sig(
76                     iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
77                     sig.output(),
78                     sig.variadic,
79                     sig.unsafety,
80                     sig.abi
81                 ))
82             }
83             ty::Generator(def_id, substs, _) => {
84                 let sig = substs.poly_sig(def_id, tcx);
85
86                 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
87                 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
88
89                 sig.map_bound(|sig| {
90                     let state_did = tcx.lang_items().gen_state().unwrap();
91                     let state_adt_ref = tcx.adt_def(state_did);
92                     let state_substs = tcx.intern_substs(&[
93                         sig.yield_ty.into(),
94                         sig.return_ty.into(),
95                     ]);
96                     let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
97
98                     tcx.mk_fn_sig(iter::once(env_ty),
99                         ret_ty,
100                         false,
101                         Unsafety::Normal,
102                         Abi::Rust
103                     )
104                 })
105             }
106             _ => bug!("unexpected type {:?} in Instance::fn_sig_noadjust", ty)
107         }
108     }
109
110     pub fn fn_sig(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::PolyFnSig<'tcx> {
111         let mut fn_sig = self.fn_sig_noadjust(tcx);
112         if let InstanceDef::VtableShim(..) = self.def {
113             // Modify fn(self, ...) to fn(self: *mut Self, ...)
114             fn_sig = fn_sig.map_bound(|mut fn_sig| {
115                 let mut inputs_and_output = fn_sig.inputs_and_output.to_vec();
116                 inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]);
117                 fn_sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
118                 fn_sig
119             });
120         }
121         fn_sig
122     }
123 }
124
125 impl<'tcx> InstanceDef<'tcx> {
126     #[inline]
127     pub fn def_id(&self) -> DefId {
128         match *self {
129             InstanceDef::Item(def_id) |
130             InstanceDef::VtableShim(def_id) |
131             InstanceDef::FnPtrShim(def_id, _) |
132             InstanceDef::Virtual(def_id, _) |
133             InstanceDef::Intrinsic(def_id, ) |
134             InstanceDef::ClosureOnceShim { call_once: def_id } |
135             InstanceDef::DropGlue(def_id, _) |
136             InstanceDef::CloneShim(def_id, _) => def_id
137         }
138     }
139
140     #[inline]
141     pub fn attrs<'a>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::Attributes<'tcx> {
142         tcx.get_attrs(self.def_id())
143     }
144
145     pub fn is_inline<'a>(
146         &self,
147         tcx: TyCtxt<'a, 'tcx, 'tcx>
148     ) -> bool {
149         use hir::map::DefPathData;
150         let def_id = match *self {
151             ty::InstanceDef::Item(def_id) => def_id,
152             ty::InstanceDef::DropGlue(_, Some(_)) => return false,
153             _ => return true
154         };
155         match tcx.def_key(def_id).disambiguated_data.data {
156             DefPathData::StructCtor |
157             DefPathData::EnumVariant(..) |
158             DefPathData::ClosureExpr => true,
159             _ => false
160         }
161     }
162
163     pub fn requires_local<'a>(
164         &self,
165         tcx: TyCtxt<'a, 'tcx, 'tcx>
166     ) -> bool {
167         if self.is_inline(tcx) {
168             return true
169         }
170         if let ty::InstanceDef::DropGlue(..) = *self {
171             // Drop glue wants to be instantiated at every codegen
172             // unit, but without an #[inline] hint. We should make this
173             // available to normal end-users.
174             return true
175         }
176         tcx.codegen_fn_attrs(self.def_id()).requests_inline()
177     }
178 }
179
180 impl<'tcx> fmt::Display for Instance<'tcx> {
181     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182         ppaux::parameterized(f, self.substs, self.def_id(), &[])?;
183         match self.def {
184             InstanceDef::Item(_) => Ok(()),
185             InstanceDef::VtableShim(_) => {
186                 write!(f, " - shim(vtable)")
187             }
188             InstanceDef::Intrinsic(_) => {
189                 write!(f, " - intrinsic")
190             }
191             InstanceDef::Virtual(_, num) => {
192                 write!(f, " - shim(#{})", num)
193             }
194             InstanceDef::FnPtrShim(_, ty) => {
195                 write!(f, " - shim({:?})", ty)
196             }
197             InstanceDef::ClosureOnceShim { .. } => {
198                 write!(f, " - shim")
199             }
200             InstanceDef::DropGlue(_, ty) => {
201                 write!(f, " - shim({:?})", ty)
202             }
203             InstanceDef::CloneShim(_, ty) => {
204                 write!(f, " - shim({:?})", ty)
205             }
206         }
207     }
208 }
209
210 impl<'a, 'b, 'tcx> Instance<'tcx> {
211     pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
212                -> Instance<'tcx> {
213         assert!(!substs.has_escaping_bound_vars(),
214                 "substs of instance {:?} not normalized for codegen: {:?}",
215                 def_id, substs);
216         Instance { def: InstanceDef::Item(def_id), substs: substs }
217     }
218
219     pub fn mono(tcx: TyCtxt<'a, 'tcx, 'b>, def_id: DefId) -> Instance<'tcx> {
220         Instance::new(def_id, tcx.global_tcx().empty_substs_for_def_id(def_id))
221     }
222
223     #[inline]
224     pub fn def_id(&self) -> DefId {
225         self.def.def_id()
226     }
227
228     /// Resolve a (def_id, substs) pair to an (optional) instance -- most commonly,
229     /// this is used to find the precise code that will run for a trait method invocation,
230     /// if known.
231     ///
232     /// Returns `None` if we cannot resolve `Instance` to a specific instance.
233     /// For example, in a context like this,
234     ///
235     /// ```
236     /// fn foo<T: Debug>(t: T) { ... }
237     /// ```
238     ///
239     /// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
240     /// know what code ought to run. (Note that this setting is also affected by the
241     /// `RevealMode` in the parameter environment.)
242     ///
243     /// Presuming that coherence and type-check have succeeded, if this method is invoked
244     /// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
245     /// `Some`.
246     pub fn resolve(tcx: TyCtxt<'a, 'tcx, 'tcx>,
247                    param_env: ty::ParamEnv<'tcx>,
248                    def_id: DefId,
249                    substs: &'tcx Substs<'tcx>) -> Option<Instance<'tcx>> {
250         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
251         let result = if let Some(trait_def_id) = tcx.trait_of_item(def_id) {
252             debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env);
253             let item = tcx.associated_item(def_id);
254             resolve_associated_item(tcx, &item, param_env, trait_def_id, substs)
255         } else {
256             let ty = tcx.type_of(def_id);
257             let item_type = tcx.subst_and_normalize_erasing_regions(
258                 substs,
259                 param_env,
260                 &ty,
261             );
262
263             let def = match item_type.sty {
264                 ty::FnDef(..) if {
265                     let f = item_type.fn_sig(tcx);
266                     f.abi() == Abi::RustIntrinsic ||
267                         f.abi() == Abi::PlatformIntrinsic
268                 } =>
269                 {
270                     debug!(" => intrinsic");
271                     ty::InstanceDef::Intrinsic(def_id)
272                 }
273                 _ => {
274                     if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
275                         let ty = substs.type_at(0);
276                         if ty.needs_drop(tcx, ty::ParamEnv::reveal_all()) {
277                             debug!(" => nontrivial drop glue");
278                             ty::InstanceDef::DropGlue(def_id, Some(ty))
279                         } else {
280                             debug!(" => trivial drop glue");
281                             ty::InstanceDef::DropGlue(def_id, None)
282                         }
283                     } else {
284                         debug!(" => free item");
285                         ty::InstanceDef::Item(def_id)
286                     }
287                 }
288             };
289             Some(Instance {
290                 def: def,
291                 substs: substs
292             })
293         };
294         debug!("resolve(def_id={:?}, substs={:?}) = {:?}", def_id, substs, result);
295         result
296     }
297
298     pub fn resolve_for_vtable(tcx: TyCtxt<'a, 'tcx, 'tcx>,
299                               param_env: ty::ParamEnv<'tcx>,
300                               def_id: DefId,
301                               substs: &'tcx Substs<'tcx>) -> Option<Instance<'tcx>> {
302         debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
303         let fn_sig = tcx.fn_sig(def_id);
304         let is_vtable_shim =
305             fn_sig.inputs().skip_binder().len() > 0 && fn_sig.input(0).skip_binder().is_self();
306         if is_vtable_shim {
307             debug!(" => associated item with unsizeable self: Self");
308             Some(Instance {
309                 def: InstanceDef::VtableShim(def_id),
310                 substs,
311             })
312         } else {
313             Instance::resolve(tcx, param_env, def_id, substs)
314         }
315     }
316
317     pub fn resolve_closure(
318         tcx: TyCtxt<'a, 'tcx, 'tcx>,
319         def_id: DefId,
320         substs: ty::ClosureSubsts<'tcx>,
321         requested_kind: ty::ClosureKind)
322         -> Instance<'tcx>
323     {
324         let actual_kind = substs.closure_kind(def_id, tcx);
325
326         match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
327             Ok(true) => fn_once_adapter_instance(tcx, def_id, substs),
328             _ => Instance::new(def_id, substs.substs)
329         }
330     }
331
332     pub fn is_vtable_shim(&self) -> bool {
333         if let InstanceDef::VtableShim(..) = self.def {
334             true
335         } else {
336             false
337         }
338     }
339 }
340
341 fn resolve_associated_item<'a, 'tcx>(
342     tcx: TyCtxt<'a, 'tcx, 'tcx>,
343     trait_item: &ty::AssociatedItem,
344     param_env: ty::ParamEnv<'tcx>,
345     trait_id: DefId,
346     rcvr_substs: &'tcx Substs<'tcx>,
347 ) -> Option<Instance<'tcx>> {
348     let def_id = trait_item.def_id;
349     debug!("resolve_associated_item(trait_item={:?}, \
350             param_env={:?}, \
351             trait_id={:?}, \
352             rcvr_substs={:?})",
353             def_id, param_env, trait_id, rcvr_substs);
354
355     let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
356     let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref)));
357
358     // Now that we know which impl is being used, we can dispatch to
359     // the actual function:
360     match vtbl {
361         traits::VtableImpl(impl_data) => {
362             let (def_id, substs) = traits::find_associated_item(
363                 tcx, param_env, trait_item, rcvr_substs, &impl_data);
364             let substs = tcx.erase_regions(&substs);
365             Some(ty::Instance::new(def_id, substs))
366         }
367         traits::VtableGenerator(generator_data) => {
368             Some(Instance {
369                 def: ty::InstanceDef::Item(generator_data.generator_def_id),
370                 substs: generator_data.substs.substs
371             })
372         }
373         traits::VtableClosure(closure_data) => {
374             let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
375             Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
376                                            trait_closure_kind))
377         }
378         traits::VtableFnPointer(ref data) => {
379             Some(Instance {
380                 def: ty::InstanceDef::FnPtrShim(trait_item.def_id, data.fn_ty),
381                 substs: rcvr_substs
382             })
383         }
384         traits::VtableObject(ref data) => {
385             let index = tcx.get_vtable_index_of_object_method(data, def_id);
386             Some(Instance {
387                 def: ty::InstanceDef::Virtual(def_id, index),
388                 substs: rcvr_substs
389             })
390         }
391         traits::VtableBuiltin(..) => {
392             if tcx.lang_items().clone_trait().is_some() {
393                 Some(Instance {
394                     def: ty::InstanceDef::CloneShim(def_id, trait_ref.self_ty()),
395                     substs: rcvr_substs
396                 })
397             } else {
398                 None
399             }
400         }
401         traits::VtableAutoImpl(..) |
402         traits::VtableParam(..) |
403         traits::VtableTraitAlias(..) => None
404     }
405 }
406
407 fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
408                                         trait_closure_kind: ty::ClosureKind)
409     -> Result<bool, ()>
410 {
411     match (actual_closure_kind, trait_closure_kind) {
412         (ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
413             (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
414             (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
415                 // No adapter needed.
416                 Ok(false)
417             }
418         (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
419             // The closure fn `llfn` is a `fn(&self, ...)`.  We want a
420             // `fn(&mut self, ...)`. In fact, at codegen time, these are
421             // basically the same thing, so we can just return llfn.
422             Ok(false)
423         }
424         (ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
425             (ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
426                 // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
427                 // self, ...)`.  We want a `fn(self, ...)`. We can produce
428                 // this by doing something like:
429                 //
430                 //     fn call_once(self, ...) { call_mut(&self, ...) }
431                 //     fn call_once(mut self, ...) { call_mut(&mut self, ...) }
432                 //
433                 // These are both the same at codegen time.
434                 Ok(true)
435         }
436         (ty::ClosureKind::FnMut, _) |
437         (ty::ClosureKind::FnOnce, _) => Err(())
438     }
439 }
440
441 fn fn_once_adapter_instance<'a, 'tcx>(
442     tcx: TyCtxt<'a, 'tcx, 'tcx>,
443     closure_did: DefId,
444     substs: ty::ClosureSubsts<'tcx>)
445     -> Instance<'tcx>
446 {
447     debug!("fn_once_adapter_shim({:?}, {:?})",
448            closure_did,
449            substs);
450     let fn_once = tcx.lang_items().fn_once_trait().unwrap();
451     let call_once = tcx.associated_items(fn_once)
452         .find(|it| it.kind == ty::AssociatedKind::Method)
453         .unwrap().def_id;
454     let def = ty::InstanceDef::ClosureOnceShim { call_once };
455
456     let self_ty = tcx.mk_closure(closure_did, substs);
457
458     let sig = substs.closure_sig(closure_did, tcx);
459     let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
460     assert_eq!(sig.inputs().len(), 1);
461     let substs = tcx.mk_substs_trait(self_ty, &[sig.inputs()[0].into()]);
462
463     debug!("fn_once_adapter_shim: self_ty={:?} sig={:?}", self_ty, sig);
464     Instance { def, substs }
465 }