1use std::fmt::Debug;
2use std::ops::ControlFlow;
34use rustc_hir::def_id::DefId;
5use rustc_infer::traits::util::PredicateSet;
6use rustc_middle::query::Providers;
7use rustc_middle::ty::{
8self, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast,
9VtblEntry,
10};
11use rustc_span::{DUMMY_SP, bug};
12use smallvec::{SmallVec, smallvec};
13use tracing::debug;
1415use crate::traits::is_vtable_safe_method;
1617#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for VtblSegment<'tcx>
{
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::MetadataDSA => VtblSegment::MetadataDSA,
Self::TraitOwnEntries { trait_ref: __self_0, emit_vptr: __self_1 }
=>
VtblSegment::TraitOwnEntries {
trait_ref: ::core::clone::Clone::clone(__self_0),
emit_vptr: ::core::clone::Clone::clone(__self_1),
},
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for VtblSegment<'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::MetadataDSA =>
::core::fmt::Formatter::write_str(f, "MetadataDSA"),
Self::TraitOwnEntries { trait_ref: __self_0, emit_vptr: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TraitOwnEntries trait_ref emit_vptr", __self_0, &__self_1),
}
}
}Debug)]
18pub enum VtblSegment<'tcx> {
19/// The segment containing Drop, Size and Align.
20MetadataDSA,
21/// A segment with the methods of a particular trait.
22TraitOwnEntries { trait_ref: ty::TraitRef<'tcx>, emit_vptr: bool },
23}
2425/// Prepare the segments for a vtable
26// FIXME: This should take a `PolyExistentialTraitRef`, since we don't care
27// about our `Self` type here.
28pub fn prepare_vtable_segments<'tcx, T>(
29 tcx: TyCtxt<'tcx>,
30 trait_ref: ty::TraitRef<'tcx>,
31 segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
32) -> Option<T> {
33prepare_vtable_segments_inner(tcx, trait_ref, segment_visitor).break_value()
34}
3536/// Helper for [`prepare_vtable_segments`] that returns `ControlFlow`,
37/// such that we can use `?` in the body.
38fn prepare_vtable_segments_inner<'tcx, T>(
39 tcx: TyCtxt<'tcx>,
40 trait_ref: ty::TraitRef<'tcx>,
41mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
42) -> ControlFlow<T> {
43// The following constraints holds for the final arrangement.
44 // 1. The whole virtual table of the first direct super trait is included as the
45 // the prefix. If this trait doesn't have any super traits, then this step
46 // consists of the dsa metadata.
47 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
48 // other super traits except those already included as part of the first
49 // direct super trait virtual table.
50 // 3. finally, the own methods of this trait.
5152 // This has the advantage that trait upcasting to the first direct super trait on each level
53 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
54 // while not using too much extra memory.
5556 // For a single inheritance relationship like this,
57 // D --> C --> B --> A
58 // The resulting vtable will consists of these segments:
59 // DSA, A, B, C, D
6061 // For a multiple inheritance relationship like this,
62 // D --> C --> A
63 // \-> B
64 // The resulting vtable will consists of these segments:
65 // DSA, A, B, B-vptr, C, D
6667 // For a diamond inheritance relationship like this,
68 // D --> B --> A
69 // \-> C -/
70 // The resulting vtable will consists of these segments:
71 // DSA, A, B, C, C-vptr, D
7273 // For a more complex inheritance relationship like this:
74 // O --> G --> C --> A
75 // \ \ \-> B
76 // | |-> F --> D
77 // | \-> E
78 // |-> N --> J --> H
79 // \ \-> I
80 // |-> M --> K
81 // \-> L
82 // The resulting vtable will consists of these segments:
83 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
84 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
85 // N, N-vptr, O
8687 // emit dsa segment first.
88segment_visitor(VtblSegment::MetadataDSA)?;
8990let mut emit_vptr_on_new_entry = false;
91let mut visited = PredicateSet::new(tcx);
92let predicate = trait_ref.upcast(tcx);
93let mut stack: SmallVec<[(ty::TraitRef<'tcx>, _, _); 5]> =
94{
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push((trait_ref, emit_vptr_on_new_entry, maybe_iter(None)));
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(trait_ref, emit_vptr_on_new_entry, maybe_iter(None))])))
}
}smallvec![(trait_ref, emit_vptr_on_new_entry, maybe_iter(None))];
95visited.insert(predicate);
9697// the main traversal loop:
98 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
99 // such that each node is emitted after all its descendants have been emitted.
100 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
101 // this is done on the fly.
102 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
103 // stops after it finds a node that has a next-sibling node.
104 // This next-sibling node will used as the starting point of next slice.
105106 // Example:
107 // For a diamond inheritance relationship like this,
108 // D#1 --> B#0 --> A#0
109 // \-> C#1 -/
110111 // Starting point 0 stack [D]
112 // Loop run #0: Stack after diving in is [D B A], A is "childless"
113 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
114 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
115 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
116 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
117 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
118 // Loop run #1: Stack after exiting out is []. Now the function exits.
119120'outer: loop {
121// dive deeper into the stack, recording the path
122'diving_in: loop {
123let &(inner_most_trait_ref, _, _) = stack.last().unwrap();
124125let mut direct_super_traits_iter = tcx126 .explicit_super_clauses_of(inner_most_trait_ref.def_id)
127 .iter_identity_copied()
128 .map(Unnormalized::skip_norm_wip)
129 .filter_map(move |(clause, _)| {
130clause131 .instantiate_supertrait(tcx, ty::Binder::dummy(inner_most_trait_ref))
132 .as_trait_clause()
133 })
134 .map(move |pred| {
135tcx.normalize_erasing_late_bound_regions(
136 ty::TypingEnv::fully_monomorphized(),
137pred,
138 )
139 .trait_ref
140 });
141142// Find an unvisited supertrait
143match direct_super_traits_iter144 .find(|&super_trait| visited.insert(super_trait.upcast(tcx)))
145 {
146// Push it to the stack for the next iteration of 'diving_in to pick up
147Some(next_super_trait) => stack.push((
148next_super_trait,
149emit_vptr_on_new_entry,
150maybe_iter(Some(direct_super_traits_iter)),
151 )),
152153// There are no more unvisited direct super traits, dive-in finished
154None => break 'diving_in,
155 }
156 }
157158// emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
159while let Some((inner_most_trait_ref, emit_vptr, mut siblings)) = stack.pop() {
160// We don't need to emit a vptr for "truly-empty" supertraits, but we *do* need to emit a
161 // vptr for supertraits that have no methods, but that themselves have supertraits
162 // with methods, so we check if any transitive supertrait has entries here (this includes
163 // the trait itself).
164let has_entries = ty::elaborate::supertrait_def_ids(tcx, inner_most_trait_ref.def_id)
165 .any(|def_id| has_own_existential_vtable_entries(tcx, def_id));
166167 segment_visitor(VtblSegment::TraitOwnEntries {
168 trait_ref: inner_most_trait_ref,
169 emit_vptr: emit_vptr && has_entries && !tcx.sess.opts.unstable_opts.no_trait_vptr,
170 })?;
171172// If we've emitted (fed to `segment_visitor`) a trait that has methods present in the vtable,
173 // we'll need to emit vptrs from now on.
174emit_vptr_on_new_entry |= has_entries;
175176if let Some(next_inner_most_trait_ref) =
177 siblings.find(|&sibling| visited.insert(sibling.upcast(tcx)))
178 {
179 stack.push((next_inner_most_trait_ref, emit_vptr_on_new_entry, siblings));
180181// just pushed a new trait onto the stack, so we need to go through its super traits
182continue 'outer;
183 }
184 }
185186// the stack is empty, all done
187return ControlFlow::Continue(());
188 }
189}
190191/// Turns option of iterator into an iterator (this is just flatten)
192fn maybe_iter<I: Iterator>(i: Option<I>) -> impl Iterator<Item = I::Item> {
193i.into_flat_iter()
194}
195196fn has_own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
197own_existential_vtable_entries_iter(tcx, trait_def_id).next().is_some()
198}
199200fn own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &[DefId] {
201tcx.arena.alloc_from_iter(own_existential_vtable_entries_iter(tcx, trait_def_id))
202}
203204fn own_existential_vtable_entries_iter(
205 tcx: TyCtxt<'_>,
206 trait_def_id: DefId,
207) -> impl Iterator<Item = DefId> {
208let trait_methods =
209tcx.associated_items(trait_def_id).in_definition_order().filter(|item| item.is_fn());
210211// Now list each method's DefId (for within its trait).
212let own_entries = trait_methods.filter_map(move |&trait_method| {
213{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:213",
"rustc_trait_selection::traits::vtable",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
::tracing_core::__macro_support::Option::Some(213u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("own_existential_vtable_entry: trait_method={0:?}",
trait_method) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
214let def_id = trait_method.def_id;
215216// Final methods should not be included in the vtable.
217if trait_method.defaultness(tcx).is_final() {
218return None;
219 }
220221// Some methods cannot be called on an object; skip those.
222if !is_vtable_safe_method(tcx, trait_def_id, trait_method) {
223{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:223",
"rustc_trait_selection::traits::vtable",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
::tracing_core::__macro_support::Option::Some(223u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("own_existential_vtable_entry: not vtable safe")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("own_existential_vtable_entry: not vtable safe");
224return None;
225 }
226227Some(def_id)
228 });
229230own_entries231}
232233/// Given a trait `trait_ref`, iterates the vtable entries
234/// that come from `trait_ref`, including its supertraits.
235fn vtable_entries<'tcx>(
236 tcx: TyCtxt<'tcx>,
237 trait_ref: ty::TraitRef<'tcx>,
238) -> &'tcx [VtblEntry<'tcx>] {
239if true {
if !(!trait_ref.has_non_region_infer() &&
!trait_ref.has_non_region_param()) {
::core::panicking::panic("assertion failed: !trait_ref.has_non_region_infer() && !trait_ref.has_non_region_param()")
};
};debug_assert!(!trait_ref.has_non_region_infer() && !trait_ref.has_non_region_param());
240tcx.debug_assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), trait_ref);
241242{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:242",
"rustc_trait_selection::traits::vtable",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
::tracing_core::__macro_support::Option::Some(242u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("vtable_entries({0:?})",
trait_ref) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("vtable_entries({:?})", trait_ref);
243244let mut entries = ::alloc::vec::Vec::new()vec![];
245246let vtable_segment_callback = |segment| -> ControlFlow<()> {
247match segment {
248 VtblSegment::MetadataDSA => {
249entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
250 }
251 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
252let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref);
253254// Lookup the shape of vtable for the trait.
255let own_existential_entries =
256tcx.own_existential_vtable_entries(existential_trait_ref.def_id);
257258let own_entries = own_existential_entries.iter().copied().map(|def_id| {
259{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:259",
"rustc_trait_selection::traits::vtable",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
::tracing_core::__macro_support::Option::Some(259u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("vtable_entries: trait_method={0:?}",
def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("vtable_entries: trait_method={:?}", def_id);
260261// The method may have some early-bound lifetimes; add regions for those.
262 // FIXME: Is this normalize needed?
263let args = tcx.normalize_erasing_regions(
264 ty::TypingEnv::fully_monomorphized(),
265Unnormalized::new_wip(GenericArgs::for_item(tcx, def_id, |param, _| {
266match param.kind {
267 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
268 GenericParamDefKind::Type { .. }
269 | GenericParamDefKind::Const { .. } => {
270trait_ref.args[param.index as usize]
271 }
272 }
273 })),
274 );
275276// It's possible that the method relies on where-clauses that
277 // do not hold for this particular set of type parameters.
278 // Note that this method could then never be called, so we
279 // do not want to try and codegen it, in that case (see #23435).
280if tcx.instantiate_and_check_impossible_clauses((def_id, args)) {
281{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:281",
"rustc_trait_selection::traits::vtable",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
::tracing_core::__macro_support::Option::Some(281u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("vtable_entries: clauses do not hold")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("vtable_entries: clauses do not hold");
282return VtblEntry::Vacant;
283 }
284285let instance = ty::Instance::expect_resolve_for_vtable(
286tcx,
287 ty::TypingEnv::fully_monomorphized(),
288def_id,
289args,
290DUMMY_SP,
291 );
292293 VtblEntry::Method(instance)
294 });
295296entries.extend(own_entries);
297298if emit_vptr {
299entries.push(VtblEntry::TraitVPtr(trait_ref));
300 }
301 }
302 }
303304 ControlFlow::Continue(())
305 };
306307let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
308309tcx.arena.alloc_from_iter(entries)
310}
311312// Given a `dyn Subtrait: Supertrait` trait ref, find corresponding first slot
313// for `Supertrait`'s methods in the vtable of `Subtrait`.
314//
315// Returns `None` if and only if an error was already reported elsewhere.
316pub(crate) fn first_method_vtable_slot<'tcx>(
317 tcx: TyCtxt<'tcx>,
318 key: ty::TraitRef<'tcx>,
319) -> Option<usize> {
320if true {
if !(!key.has_non_region_infer() && !key.has_non_region_param()) {
::core::panicking::panic("assertion failed: !key.has_non_region_infer() && !key.has_non_region_param()")
};
};debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
321tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), key);
322323let ty::Dynamic(source, _) = *key.self_ty().kind() else {
324::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());bug!();
325 };
326let source_principal = tcx.instantiate_bound_regions_with_erased(
327source.principal().unwrap().with_self_ty(tcx, key.self_ty()),
328 );
329330// We're monomorphizing a call to a dyn trait object that can never be constructed.
331if tcx332 .instantiate_and_check_impossible_clauses((source_principal.def_id, source_principal.args))
333 {
334return Some(0);
335 }
336337let target_principal = ty::ExistentialTraitRef::erase_self_ty(tcx, key);
338339let vtable_segment_callback = {
340let mut vptr_offset = 0;
341move |segment| {
342match segment {
343 VtblSegment::MetadataDSA => {
344vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
345 }
346 VtblSegment::TraitOwnEntries { trait_ref: vtable_principal, emit_vptr } => {
347if ty::ExistentialTraitRef::erase_self_ty(tcx, vtable_principal)
348 == target_principal349 {
350return ControlFlow::Break(vptr_offset);
351 }
352353vptr_offset +=
354tcx.own_existential_vtable_entries(vtable_principal.def_id).len();
355356if emit_vptr {
357vptr_offset += 1;
358 }
359 }
360 }
361 ControlFlow::Continue(())
362 }
363 };
364365let index = prepare_vtable_segments(tcx, source_principal, vtable_segment_callback);
366367if index.is_none() {
368// This can happen if the trait hierarchy is malformed (e.g., due to
369 // missing generics on a supertrait bound). There should already be an error
370 // emitted for this, so we just delay the ICE.
371tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not find the supertrait vtable slot for `{0}` -> `{1}`",
source, target_principal))
})format!(
372"could not find the supertrait vtable slot for `{}` -> `{}`",
373 source, target_principal
374 ));
375 }
376377index378}
379380/// Given a `dyn Subtrait` and `dyn Supertrait` trait object, find the slot of
381/// the trait vptr in the subtrait's vtable.
382///
383/// A return value of `None` means that the original vtable can be reused.
384pub(crate) fn supertrait_vtable_slot<'tcx>(
385 tcx: TyCtxt<'tcx>,
386 key: (
387Ty<'tcx>, // Source -- `dyn Subtrait`.
388Ty<'tcx>, // Target -- `dyn Supertrait` being coerced to.
389),
390) -> Option<usize> {
391if true {
if !(!key.has_non_region_infer() && !key.has_non_region_param()) {
::core::panicking::panic("assertion failed: !key.has_non_region_infer() && !key.has_non_region_param()")
};
};debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
392tcx.debug_assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), key);
393394let (source, target) = key;
395396// If the target principal is `None`, we can just return `None`.
397let ty::Dynamic(target_data, _) = *target.kind() else {
398::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());bug!();
399 };
400let target_principal = tcx.instantiate_bound_regions_with_erased(target_data.principal()?);
401402// Given that we have a target principal, it is a bug for there not to be a source principal.
403let ty::Dynamic(source_data, _) = *source.kind() else {
404::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller());bug!();
405 };
406let source_principal = tcx.instantiate_bound_regions_with_erased(
407source_data.principal().unwrap().with_self_ty(tcx, source),
408 );
409410// We're monomorphizing a dyn trait object upcast that can never be constructed.
411if tcx412 .instantiate_and_check_impossible_clauses((source_principal.def_id, source_principal.args))
413 {
414return None;
415 }
416417let vtable_segment_callback = {
418let mut vptr_offset = 0;
419move |segment| {
420match segment {
421 VtblSegment::MetadataDSA => {
422vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
423 }
424 VtblSegment::TraitOwnEntries { trait_ref: vtable_principal, emit_vptr } => {
425vptr_offset +=
426tcx.own_existential_vtable_entries(vtable_principal.def_id).len();
427if ty::ExistentialTraitRef::erase_self_ty(tcx, vtable_principal)
428 == target_principal429 {
430if emit_vptr {
431return ControlFlow::Break(Some(vptr_offset));
432 } else {
433return ControlFlow::Break(None);
434 }
435 }
436437if emit_vptr {
438vptr_offset += 1;
439 }
440 }
441 }
442 ControlFlow::Continue(())
443 }
444 };
445446prepare_vtable_segments(tcx, source_principal, vtable_segment_callback).unwrap_or_else(|| {
447// This can happen if the trait hierarchy is malformed (e.g., due to
448 // missing generics on a supertrait bound). There should already be an error
449 // emitted for this, so we just delay the ICE.
450tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not find the supertrait vtable slot for `{0}` -> `{1}`",
source, target))
})format!(
451"could not find the supertrait vtable slot for `{}` -> `{}`",
452 source, target
453 ));
454None455 })
456}
457458/// Returns the traits that are prefixes of this vtable, such that upcasting to these traits
459/// reuses the vtable pointer unchanged.
460///
461/// For a `trait Foo: A + B`, the methods for A are stored as a prefix to the vtable for Foo.
462/// If B has no methods, it is also part of this prefix (although it takes up no space).
463///
464/// This function returns the full set of these traits (A might have its own supertrait, etc.).
465/// The input trait is the last element of the output vector.
466pub fn vtable_prefix_traits<'tcx>(
467 tcx: TyCtxt<'tcx>,
468 key: ty::TraitRef<'tcx>,
469) -> Vec<ty::ExistentialTraitRef<'tcx>> {
470if true {
if !(!key.has_non_region_infer() && !key.has_non_region_param()) {
::core::panicking::panic("assertion failed: !key.has_non_region_infer() && !key.has_non_region_param()")
};
};debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
471472let mut entries = ::alloc::vec::Vec::new()vec![];
473474let vtable_segment_callback = |segment| -> ControlFlow<()> {
475// When `emit_vptr: false`, this trait's vtable is a prefix of `key`'s vtable.
476if let VtblSegment::TraitOwnEntries { trait_ref, emit_vptr: false } = segment {
477entries.push(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
478 }
479480 ControlFlow::Continue(())
481 };
482483let _ = prepare_vtable_segments(tcx, key, vtable_segment_callback);
484485// The input trait is the last element in the output vector.
486if true {
{
match (&entries.last(),
&Some(&ty::ExistentialTraitRef::erase_self_ty(tcx, key))) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(entries.last(), Some(&ty::ExistentialTraitRef::erase_self_ty(tcx, key)));
487488entries489}
490491pub(super) fn provide(providers: &mut Providers) {
492*providers = Providers {
493own_existential_vtable_entries,
494vtable_entries,
495first_method_vtable_slot,
496supertrait_vtable_slot,
497 ..*providers498 };
499}