1use std::assert_matches::assert_matches;
2use std::fmt;
3use std::path::PathBuf;
4
5use rustc_data_structures::fx::FxHashMap;
6use rustc_errors::ErrorGuaranteed;
7use rustc_hir as hir;
8use rustc_hir::def::{CtorKind, DefKind, Namespace};
9use rustc_hir::def_id::{CrateNum, DefId};
10use rustc_hir::lang_items::LangItem;
11use rustc_index::bit_set::FiniteBitSet;
12use rustc_macros::{Decodable, Encodable, HashStable, Lift, TyDecodable, TyEncodable};
13use rustc_span::def_id::LOCAL_CRATE;
14use rustc_span::{DUMMY_SP, Span, Symbol};
15use tracing::{debug, instrument};
16
17use crate::error;
18use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
19use crate::ty::normalize_erasing_regions::NormalizationError;
20use crate::ty::print::{FmtPrinter, Printer, shrunk_instance_name};
21use crate::ty::{
22 self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
23 TypeVisitable, TypeVisitableExt, TypeVisitor,
24};
25
26#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)]
35#[derive(HashStable, Lift, TypeFoldable, TypeVisitable)]
36pub struct Instance<'tcx> {
37 pub def: InstanceKind<'tcx>,
38 pub args: GenericArgsRef<'tcx>,
39}
40
41#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
47#[derive(TyEncodable, TyDecodable, HashStable)]
48pub enum ReifyReason {
49 FnPtr,
57 Vtable,
61}
62
63#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
64#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable, Lift)]
65pub enum InstanceKind<'tcx> {
66 Item(DefId),
73
74 Intrinsic(DefId),
80
81 VTableShim(DefId),
87
88 ReifyShim(DefId, Option<ReifyReason>),
106
107 FnPtrShim(DefId, Ty<'tcx>),
111
112 Virtual(DefId, usize),
120
121 ClosureOnceShim { call_once: DefId, track_caller: bool },
128
129 ConstructCoroutineInClosureShim {
135 coroutine_closure_def_id: DefId,
136 receiver_by_ref: bool,
142 },
143
144 ThreadLocalShim(DefId),
148
149 DropGlue(DefId, Option<Ty<'tcx>>),
155
156 CloneShim(DefId, Ty<'tcx>),
163
164 FnPtrAddrShim(DefId, Ty<'tcx>),
170
171 AsyncDropGlueCtorShim(DefId, Option<Ty<'tcx>>),
176}
177
178impl<'tcx> Instance<'tcx> {
179 pub fn ty(&self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
182 let ty = tcx.type_of(self.def.def_id());
183 tcx.instantiate_and_normalize_erasing_regions(self.args, typing_env, ty)
184 }
185
186 pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum> {
193 if self.def_id().is_local() {
196 return None;
197 }
198
199 if !tcx.sess.opts.share_generics()
203 && tcx.codegen_fn_attrs(self.def_id()).inline != rustc_attr_parsing::InlineAttr::Never
206 {
207 return None;
208 }
209
210 self.args.non_erasable_generics().next()?;
212
213 if tcx.is_compiler_builtins(LOCAL_CRATE) {
215 return None;
216 }
217
218 match self.def {
219 InstanceKind::Item(def) => tcx
220 .upstream_monomorphizations_for(def)
221 .and_then(|monos| monos.get(&self.args).cloned()),
222 InstanceKind::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.args),
223 InstanceKind::AsyncDropGlueCtorShim(_, Some(_)) => {
224 tcx.upstream_async_drop_glue_for(self.args)
225 }
226 _ => None,
227 }
228 }
229}
230
231impl<'tcx> InstanceKind<'tcx> {
232 #[inline]
233 pub fn def_id(self) -> DefId {
234 match self {
235 InstanceKind::Item(def_id)
236 | InstanceKind::VTableShim(def_id)
237 | InstanceKind::ReifyShim(def_id, _)
238 | InstanceKind::FnPtrShim(def_id, _)
239 | InstanceKind::Virtual(def_id, _)
240 | InstanceKind::Intrinsic(def_id)
241 | InstanceKind::ThreadLocalShim(def_id)
242 | InstanceKind::ClosureOnceShim { call_once: def_id, track_caller: _ }
243 | ty::InstanceKind::ConstructCoroutineInClosureShim {
244 coroutine_closure_def_id: def_id,
245 receiver_by_ref: _,
246 }
247 | InstanceKind::DropGlue(def_id, _)
248 | InstanceKind::CloneShim(def_id, _)
249 | InstanceKind::FnPtrAddrShim(def_id, _)
250 | InstanceKind::AsyncDropGlueCtorShim(def_id, _) => def_id,
251 }
252 }
253
254 pub fn def_id_if_not_guaranteed_local_codegen(self) -> Option<DefId> {
256 match self {
257 ty::InstanceKind::Item(def) => Some(def),
258 ty::InstanceKind::DropGlue(def_id, Some(_))
259 | InstanceKind::AsyncDropGlueCtorShim(def_id, Some(_))
260 | InstanceKind::ThreadLocalShim(def_id) => Some(def_id),
261 InstanceKind::VTableShim(..)
262 | InstanceKind::ReifyShim(..)
263 | InstanceKind::FnPtrShim(..)
264 | InstanceKind::Virtual(..)
265 | InstanceKind::Intrinsic(..)
266 | InstanceKind::ClosureOnceShim { .. }
267 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
268 | InstanceKind::DropGlue(..)
269 | InstanceKind::AsyncDropGlueCtorShim(..)
270 | InstanceKind::CloneShim(..)
271 | InstanceKind::FnPtrAddrShim(..) => None,
272 }
273 }
274
275 #[inline]
276 pub fn get_attrs(
277 &self,
278 tcx: TyCtxt<'tcx>,
279 attr: Symbol,
280 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
281 tcx.get_attrs(self.def_id(), attr)
282 }
283
284 pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
290 use rustc_hir::definitions::DefPathData;
291 let def_id = match *self {
292 ty::InstanceKind::Item(def) => def,
293 ty::InstanceKind::DropGlue(_, Some(_)) => return false,
294 ty::InstanceKind::AsyncDropGlueCtorShim(_, Some(_)) => return false,
295 ty::InstanceKind::ThreadLocalShim(_) => return false,
296 _ => return true,
297 };
298 matches!(
299 tcx.def_key(def_id).disambiguated_data.data,
300 DefPathData::Ctor | DefPathData::Closure
301 )
302 }
303
304 pub fn generates_cgu_internal_copy(&self, tcx: TyCtxt<'tcx>) -> bool {
312 if self.requires_inline(tcx) {
313 return true;
314 }
315 if let ty::InstanceKind::DropGlue(.., Some(ty))
316 | ty::InstanceKind::AsyncDropGlueCtorShim(.., Some(ty)) = *self
317 {
318 if tcx.sess.opts.incremental.is_none() {
322 return true;
323 }
324 return ty.ty_adt_def().is_none_or(|adt_def| {
332 match *self {
333 ty::InstanceKind::DropGlue(..) => adt_def.destructor(tcx).map(|dtor| dtor.did),
334 ty::InstanceKind::AsyncDropGlueCtorShim(..) => {
335 adt_def.async_destructor(tcx).map(|dtor| dtor.ctor)
336 }
337 _ => unreachable!(),
338 }
339 .map_or_else(|| adt_def.is_enum(), |did| tcx.cross_crate_inlinable(did))
340 });
341 }
342 if let ty::InstanceKind::ThreadLocalShim(..) = *self {
343 return false;
344 }
345 tcx.cross_crate_inlinable(self.def_id())
346 }
347
348 pub fn requires_caller_location(&self, tcx: TyCtxt<'_>) -> bool {
349 match *self {
350 InstanceKind::Item(def_id) | InstanceKind::Virtual(def_id, _) => {
351 tcx.body_codegen_attrs(def_id).flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
352 }
353 InstanceKind::ClosureOnceShim { call_once: _, track_caller } => track_caller,
354 _ => false,
355 }
356 }
357
358 pub fn has_polymorphic_mir_body(&self) -> bool {
365 match *self {
366 InstanceKind::CloneShim(..)
367 | InstanceKind::ThreadLocalShim(..)
368 | InstanceKind::FnPtrAddrShim(..)
369 | InstanceKind::FnPtrShim(..)
370 | InstanceKind::DropGlue(_, Some(_))
371 | InstanceKind::AsyncDropGlueCtorShim(_, Some(_)) => false,
372 InstanceKind::ClosureOnceShim { .. }
373 | InstanceKind::ConstructCoroutineInClosureShim { .. }
374 | InstanceKind::DropGlue(..)
375 | InstanceKind::AsyncDropGlueCtorShim(..)
376 | InstanceKind::Item(_)
377 | InstanceKind::Intrinsic(..)
378 | InstanceKind::ReifyShim(..)
379 | InstanceKind::Virtual(..)
380 | InstanceKind::VTableShim(..) => true,
381 }
382 }
383}
384
385fn type_length<'tcx>(item: impl TypeVisitable<TyCtxt<'tcx>>) -> usize {
386 struct Visitor<'tcx> {
387 type_length: usize,
388 cache: FxHashMap<Ty<'tcx>, usize>,
389 }
390 impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Visitor<'tcx> {
391 fn visit_ty(&mut self, t: Ty<'tcx>) {
392 if let Some(&value) = self.cache.get(&t) {
393 self.type_length += value;
394 return;
395 }
396
397 let prev = self.type_length;
398 self.type_length += 1;
399 t.super_visit_with(self);
400
401 if self.type_length > 16 {
403 self.cache.insert(t, self.type_length - prev);
404 }
405 }
406
407 fn visit_const(&mut self, ct: ty::Const<'tcx>) {
408 self.type_length += 1;
409 ct.super_visit_with(self);
410 }
411 }
412 let mut visitor = Visitor { type_length: 0, cache: Default::default() };
413 item.visit_with(&mut visitor);
414
415 visitor.type_length
416}
417
418pub fn fmt_instance(
419 f: &mut fmt::Formatter<'_>,
420 instance: Instance<'_>,
421 type_length: Option<rustc_session::Limit>,
422) -> fmt::Result {
423 ty::tls::with(|tcx| {
424 let args = tcx.lift(instance.args).expect("could not lift for printing");
425
426 let mut cx = if let Some(type_length) = type_length {
427 FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length)
428 } else {
429 FmtPrinter::new(tcx, Namespace::ValueNS)
430 };
431 cx.print_def_path(instance.def_id(), args)?;
432 let s = cx.into_buffer();
433 f.write_str(&s)
434 })?;
435
436 match instance.def {
437 InstanceKind::Item(_) => Ok(()),
438 InstanceKind::VTableShim(_) => write!(f, " - shim(vtable)"),
439 InstanceKind::ReifyShim(_, None) => write!(f, " - shim(reify)"),
440 InstanceKind::ReifyShim(_, Some(ReifyReason::FnPtr)) => write!(f, " - shim(reify-fnptr)"),
441 InstanceKind::ReifyShim(_, Some(ReifyReason::Vtable)) => write!(f, " - shim(reify-vtable)"),
442 InstanceKind::ThreadLocalShim(_) => write!(f, " - shim(tls)"),
443 InstanceKind::Intrinsic(_) => write!(f, " - intrinsic"),
444 InstanceKind::Virtual(_, num) => write!(f, " - virtual#{num}"),
445 InstanceKind::FnPtrShim(_, ty) => write!(f, " - shim({ty})"),
446 InstanceKind::ClosureOnceShim { .. } => write!(f, " - shim"),
447 InstanceKind::ConstructCoroutineInClosureShim { .. } => write!(f, " - shim"),
448 InstanceKind::DropGlue(_, None) => write!(f, " - shim(None)"),
449 InstanceKind::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({ty}))"),
450 InstanceKind::CloneShim(_, ty) => write!(f, " - shim({ty})"),
451 InstanceKind::FnPtrAddrShim(_, ty) => write!(f, " - shim({ty})"),
452 InstanceKind::AsyncDropGlueCtorShim(_, None) => write!(f, " - shim(None)"),
453 InstanceKind::AsyncDropGlueCtorShim(_, Some(ty)) => write!(f, " - shim(Some({ty}))"),
454 }
455}
456
457pub struct ShortInstance<'tcx>(pub Instance<'tcx>, pub usize);
458
459impl<'tcx> fmt::Display for ShortInstance<'tcx> {
460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461 fmt_instance(f, self.0, Some(rustc_session::Limit(self.1)))
462 }
463}
464
465impl<'tcx> fmt::Display for Instance<'tcx> {
466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467 fmt_instance(f, *self, None)
468 }
469}
470
471impl<'tcx> Instance<'tcx> {
472 pub fn new(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> {
473 assert!(
474 !args.has_escaping_bound_vars(),
475 "args of instance {def_id:?} has escaping bound vars: {args:?}"
476 );
477 Instance { def: InstanceKind::Item(def_id), args }
478 }
479
480 pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> {
481 let args = GenericArgs::for_item(tcx, def_id, |param, _| match param.kind {
482 ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
483 ty::GenericParamDefKind::Type { .. } => {
484 bug!("Instance::mono: {:?} has type parameters", def_id)
485 }
486 ty::GenericParamDefKind::Const { .. } => {
487 bug!("Instance::mono: {:?} has const parameters", def_id)
488 }
489 });
490
491 Instance::new(def_id, args)
492 }
493
494 #[inline]
495 pub fn def_id(&self) -> DefId {
496 self.def.def_id()
497 }
498
499 #[instrument(level = "debug", skip(tcx), ret)]
525 pub fn try_resolve(
526 tcx: TyCtxt<'tcx>,
527 typing_env: ty::TypingEnv<'tcx>,
528 def_id: DefId,
529 args: GenericArgsRef<'tcx>,
530 ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> {
531 assert_matches!(
532 tcx.def_kind(def_id),
533 DefKind::Fn
534 | DefKind::AssocFn
535 | DefKind::Const
536 | DefKind::AssocConst
537 | DefKind::AnonConst
538 | DefKind::InlineConst
539 | DefKind::Static { .. }
540 | DefKind::Ctor(_, CtorKind::Fn)
541 | DefKind::Closure
542 | DefKind::SyntheticCoroutineBody,
543 "`Instance::try_resolve` should only be used to resolve instances of \
544 functions, statics, and consts; to resolve associated types, use \
545 `try_normalize_erasing_regions`."
546 );
547
548 if tcx.sess.opts.unstable_opts.enforce_type_length_limit
555 && !tcx.type_length_limit().value_within_limit(type_length(args))
556 {
557 return Ok(None);
558 }
559
560 tcx.resolve_instance_raw(tcx.erase_regions(typing_env.as_query_input((def_id, args))))
563 }
564
565 pub fn expect_resolve(
566 tcx: TyCtxt<'tcx>,
567 typing_env: ty::TypingEnv<'tcx>,
568 def_id: DefId,
569 args: GenericArgsRef<'tcx>,
570 span: Span,
571 ) -> Instance<'tcx> {
572 let span_or_local_def_span =
576 || if span.is_dummy() && def_id.is_local() { tcx.def_span(def_id) } else { span };
577
578 match ty::Instance::try_resolve(tcx, typing_env, def_id, args) {
579 Ok(Some(instance)) => instance,
580 Ok(None) => {
581 let type_length = type_length(args);
582 if !tcx.type_length_limit().value_within_limit(type_length) {
583 let (shrunk, written_to_path) =
584 shrunk_instance_name(tcx, Instance::new(def_id, args));
585 let mut path = PathBuf::new();
586 let was_written = if let Some(path2) = written_to_path {
587 path = path2;
588 true
589 } else {
590 false
591 };
592 tcx.dcx().emit_fatal(error::TypeLengthLimit {
593 span: span_or_local_def_span(),
597 shrunk,
598 was_written,
599 path,
600 type_length,
601 });
602 } else {
603 span_bug!(
604 span_or_local_def_span(),
605 "failed to resolve instance for {}",
606 tcx.def_path_str_with_args(def_id, args)
607 )
608 }
609 }
610 instance => span_bug!(
611 span_or_local_def_span(),
612 "failed to resolve instance for {}: {instance:#?}",
613 tcx.def_path_str_with_args(def_id, args)
614 ),
615 }
616 }
617
618 pub fn resolve_for_fn_ptr(
619 tcx: TyCtxt<'tcx>,
620 typing_env: ty::TypingEnv<'tcx>,
621 def_id: DefId,
622 args: GenericArgsRef<'tcx>,
623 ) -> Option<Instance<'tcx>> {
624 debug!("resolve(def_id={:?}, args={:?})", def_id, args);
625 assert!(!tcx.is_closure_like(def_id), "Called `resolve_for_fn_ptr` on closure: {def_id:?}");
627 let reason = tcx.sess.is_sanitizer_kcfi_enabled().then_some(ReifyReason::FnPtr);
628 Instance::try_resolve(tcx, typing_env, def_id, args).ok().flatten().map(|mut resolved| {
629 match resolved.def {
630 InstanceKind::Item(def) if resolved.def.requires_caller_location(tcx) => {
631 debug!(" => fn pointer created for function with #[track_caller]");
632 resolved.def = InstanceKind::ReifyShim(def, reason);
633 }
634 InstanceKind::Virtual(def_id, _) => {
635 debug!(" => fn pointer created for virtual call");
636 resolved.def = InstanceKind::ReifyShim(def_id, reason);
637 }
638 _ if tcx.sess.is_sanitizer_kcfi_enabled()
641 && tcx
642 .opt_associated_item(def_id)
643 .and_then(|assoc| assoc.trait_item_def_id)
644 .is_some() =>
645 {
646 resolved.def = InstanceKind::ReifyShim(resolved.def_id(), reason)
649 }
650 _ if tcx.sess.is_sanitizer_kcfi_enabled()
652 && tcx.is_closure_like(resolved.def_id()) =>
653 {
654 resolved = Instance { def: InstanceKind::ReifyShim(def_id, reason), args }
658 }
659 _ => {}
660 }
661
662 resolved
663 })
664 }
665
666 pub fn expect_resolve_for_vtable(
667 tcx: TyCtxt<'tcx>,
668 typing_env: ty::TypingEnv<'tcx>,
669 def_id: DefId,
670 args: GenericArgsRef<'tcx>,
671 span: Span,
672 ) -> Instance<'tcx> {
673 debug!("resolve_for_vtable(def_id={:?}, args={:?})", def_id, args);
674 let fn_sig = tcx.fn_sig(def_id).instantiate_identity();
675 let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty()
676 && fn_sig.input(0).skip_binder().is_param(0)
677 && tcx.generics_of(def_id).has_self;
678
679 if is_vtable_shim {
680 debug!(" => associated item with unsizeable self: Self");
681 return Instance { def: InstanceKind::VTableShim(def_id), args };
682 }
683
684 let mut resolved = Instance::expect_resolve(tcx, typing_env, def_id, args, span);
685
686 let reason = tcx.sess.is_sanitizer_kcfi_enabled().then_some(ReifyReason::Vtable);
687 match resolved.def {
688 InstanceKind::Item(def) => {
689 let needs_track_caller_shim = resolved.def.requires_caller_location(tcx)
699 && !tcx.should_inherit_track_caller(def)
702 && !matches!(
708 tcx.opt_associated_item(def),
709 Some(ty::AssocItem {
710 container: ty::AssocItemContainer::Trait,
711 ..
712 })
713 );
714 let needs_rpitit_shim =
716 tcx.return_position_impl_trait_in_trait_shim_data(def).is_some();
717 if needs_track_caller_shim || needs_rpitit_shim {
718 if tcx.is_closure_like(def) {
719 debug!(
720 " => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}",
721 def, def_id, args
722 );
723
724 resolved = Instance { def: InstanceKind::ReifyShim(def_id, reason), args };
728 } else {
729 debug!(
730 " => vtable fn pointer created for function with #[track_caller]: {:?}",
731 def
732 );
733 resolved.def = InstanceKind::ReifyShim(def, reason);
734 }
735 }
736 }
737 InstanceKind::Virtual(def_id, _) => {
738 debug!(" => vtable fn pointer created for virtual call");
739 resolved.def = InstanceKind::ReifyShim(def_id, reason)
740 }
741 _ => {}
742 }
743
744 resolved
745 }
746
747 pub fn resolve_closure(
748 tcx: TyCtxt<'tcx>,
749 def_id: DefId,
750 args: ty::GenericArgsRef<'tcx>,
751 requested_kind: ty::ClosureKind,
752 ) -> Instance<'tcx> {
753 let actual_kind = args.as_closure().kind();
754
755 match needs_fn_once_adapter_shim(actual_kind, requested_kind) {
756 Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, args),
757 _ => Instance::new(def_id, args),
758 }
759 }
760
761 pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
762 let def_id = tcx.require_lang_item(LangItem::DropInPlace, None);
763 let args = tcx.mk_args(&[ty.into()]);
764 Instance::expect_resolve(
765 tcx,
766 ty::TypingEnv::fully_monomorphized(),
767 def_id,
768 args,
769 ty.ty_adt_def().and_then(|adt| tcx.hir().span_if_local(adt.did())).unwrap_or(DUMMY_SP),
770 )
771 }
772
773 pub fn resolve_async_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
774 let def_id = tcx.require_lang_item(LangItem::AsyncDropInPlace, None);
775 let args = tcx.mk_args(&[ty.into()]);
776 Instance::expect_resolve(
777 tcx,
778 ty::TypingEnv::fully_monomorphized(),
779 def_id,
780 args,
781 ty.ty_adt_def().and_then(|adt| tcx.hir().span_if_local(adt.did())).unwrap_or(DUMMY_SP),
782 )
783 }
784
785 #[instrument(level = "debug", skip(tcx), ret)]
786 pub fn fn_once_adapter_instance(
787 tcx: TyCtxt<'tcx>,
788 closure_did: DefId,
789 args: ty::GenericArgsRef<'tcx>,
790 ) -> Instance<'tcx> {
791 let fn_once = tcx.require_lang_item(LangItem::FnOnce, None);
792 let call_once = tcx
793 .associated_items(fn_once)
794 .in_definition_order()
795 .find(|it| it.kind == ty::AssocKind::Fn)
796 .unwrap()
797 .def_id;
798 let track_caller =
799 tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER);
800 let def = ty::InstanceKind::ClosureOnceShim { call_once, track_caller };
801
802 let self_ty = Ty::new_closure(tcx, closure_did, args);
803
804 let tupled_inputs_ty = args.as_closure().sig().map_bound(|sig| sig.inputs()[0]);
805 let tupled_inputs_ty = tcx.instantiate_bound_regions_with_erased(tupled_inputs_ty);
806 let args = tcx.mk_args_trait(self_ty, [tupled_inputs_ty.into()]);
807
808 debug!(?self_ty, args=?tupled_inputs_ty.tuple_fields());
809 Instance { def, args }
810 }
811
812 pub fn try_resolve_item_for_coroutine(
813 tcx: TyCtxt<'tcx>,
814 trait_item_id: DefId,
815 trait_id: DefId,
816 rcvr_args: ty::GenericArgsRef<'tcx>,
817 ) -> Option<Instance<'tcx>> {
818 let ty::Coroutine(coroutine_def_id, args) = *rcvr_args.type_at(0).kind() else {
819 return None;
820 };
821 let coroutine_kind = tcx.coroutine_kind(coroutine_def_id).unwrap();
822
823 let coroutine_callable_item = if tcx.is_lang_item(trait_id, LangItem::Future) {
824 assert_matches!(
825 coroutine_kind,
826 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
827 );
828 hir::LangItem::FuturePoll
829 } else if tcx.is_lang_item(trait_id, LangItem::Iterator) {
830 assert_matches!(
831 coroutine_kind,
832 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
833 );
834 hir::LangItem::IteratorNext
835 } else if tcx.is_lang_item(trait_id, LangItem::AsyncIterator) {
836 assert_matches!(
837 coroutine_kind,
838 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)
839 );
840 hir::LangItem::AsyncIteratorPollNext
841 } else if tcx.is_lang_item(trait_id, LangItem::Coroutine) {
842 assert_matches!(coroutine_kind, hir::CoroutineKind::Coroutine(_));
843 hir::LangItem::CoroutineResume
844 } else {
845 return None;
846 };
847
848 if tcx.is_lang_item(trait_item_id, coroutine_callable_item) {
849 let ty::Coroutine(_, id_args) = *tcx.type_of(coroutine_def_id).skip_binder().kind()
850 else {
851 bug!()
852 };
853
854 if args.as_coroutine().kind_ty() == id_args.as_coroutine().kind_ty() {
857 Some(Instance { def: ty::InstanceKind::Item(coroutine_def_id), args })
858 } else {
859 Some(Instance {
860 def: ty::InstanceKind::Item(
861 tcx.coroutine_by_move_body_def_id(coroutine_def_id),
862 ),
863 args,
864 })
865 }
866 } else {
867 debug_assert!(tcx.defaultness(trait_item_id).has_value());
871 Some(Instance::new(trait_item_id, rcvr_args))
872 }
873 }
874
875 fn args_for_mir_body(&self) -> Option<GenericArgsRef<'tcx>> {
886 self.def.has_polymorphic_mir_body().then_some(self.args)
887 }
888
889 pub fn instantiate_mir<T>(&self, tcx: TyCtxt<'tcx>, v: EarlyBinder<'tcx, &T>) -> T
890 where
891 T: TypeFoldable<TyCtxt<'tcx>> + Copy,
892 {
893 let v = v.map_bound(|v| *v);
894 if let Some(args) = self.args_for_mir_body() {
895 v.instantiate(tcx, args)
896 } else {
897 v.instantiate_identity()
898 }
899 }
900
901 #[inline(always)]
902 pub fn instantiate_mir_and_normalize_erasing_regions<T>(
904 &self,
905 tcx: TyCtxt<'tcx>,
906 typing_env: ty::TypingEnv<'tcx>,
907 v: EarlyBinder<'tcx, T>,
908 ) -> T
909 where
910 T: TypeFoldable<TyCtxt<'tcx>>,
911 {
912 if let Some(args) = self.args_for_mir_body() {
913 tcx.instantiate_and_normalize_erasing_regions(args, typing_env, v)
914 } else {
915 tcx.normalize_erasing_regions(typing_env, v.instantiate_identity())
916 }
917 }
918
919 #[inline(always)]
920 pub fn try_instantiate_mir_and_normalize_erasing_regions<T>(
922 &self,
923 tcx: TyCtxt<'tcx>,
924 typing_env: ty::TypingEnv<'tcx>,
925 v: EarlyBinder<'tcx, T>,
926 ) -> Result<T, NormalizationError<'tcx>>
927 where
928 T: TypeFoldable<TyCtxt<'tcx>>,
929 {
930 if let Some(args) = self.args_for_mir_body() {
931 tcx.try_instantiate_and_normalize_erasing_regions(args, typing_env, v)
932 } else {
933 tcx.try_normalize_erasing_regions(typing_env, v.instantiate_identity())
939 }
940 }
941}
942
943fn needs_fn_once_adapter_shim(
944 actual_closure_kind: ty::ClosureKind,
945 trait_closure_kind: ty::ClosureKind,
946) -> Result<bool, ()> {
947 match (actual_closure_kind, trait_closure_kind) {
948 (ty::ClosureKind::Fn, ty::ClosureKind::Fn)
949 | (ty::ClosureKind::FnMut, ty::ClosureKind::FnMut)
950 | (ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
951 Ok(false)
953 }
954 (ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
955 Ok(false)
959 }
960 (ty::ClosureKind::Fn | ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
961 Ok(true)
970 }
971 (ty::ClosureKind::FnMut | ty::ClosureKind::FnOnce, _) => Err(()),
972 }
973}
974
975#[derive(Debug, Copy, Clone, Eq, PartialEq, Decodable, Encodable, HashStable)]
978pub struct UnusedGenericParams(FiniteBitSet<u32>);
979
980impl Default for UnusedGenericParams {
981 fn default() -> Self {
982 UnusedGenericParams::new_all_used()
983 }
984}
985
986impl UnusedGenericParams {
987 pub fn new_all_unused(amount: u32) -> Self {
988 let mut bitset = FiniteBitSet::new_empty();
989 bitset.set_range(0..amount);
990 Self(bitset)
991 }
992
993 pub fn new_all_used() -> Self {
994 Self(FiniteBitSet::new_empty())
995 }
996
997 pub fn mark_used(&mut self, idx: u32) {
998 self.0.clear(idx);
999 }
1000
1001 pub fn is_unused(&self, idx: u32) -> bool {
1002 self.0.contains(idx).unwrap_or(false)
1003 }
1004
1005 pub fn is_used(&self, idx: u32) -> bool {
1006 !self.is_unused(idx)
1007 }
1008
1009 pub fn all_used(&self) -> bool {
1010 self.0.is_empty()
1011 }
1012
1013 pub fn bits(&self) -> u32 {
1014 self.0.0
1015 }
1016
1017 pub fn from_bits(bits: u32) -> UnusedGenericParams {
1018 UnusedGenericParams(FiniteBitSet(bits))
1019 }
1020}