Skip to content

Commit e2867c9

Browse files
Rollup merge of #165396 - Jamesbarford:perf/intern-type-kind, r=nnethercote
Perf - Separate flag computation & intern functions per `TyKind` Create a separate function for interning each `TyKind` and an individual flags computation function. Doing this means that we can avoid a match statement that previously existed when computing flags which improves perf; #165396 (comment) Separately there might be some wins with splitting out the `InternedSet`'s (see 'Original Description' below) however, in my view, there is enough of a benefit with this relatively simple change that modifying the `InternedSet`'s could be a separate exploration. **Edit:** My original write up for the PR is below. However what this PR has become and what the original intention was has drifted sufficiently that writing a new description made the most sense to me. <details> <summary> Original Description</summary> Create an `InternedSet` per `TyKind` variant; this is something I discussed with @lqd & @lcnr separately, both thought it was a reasonable idea. I believe the speedup comes from no longer having to check the `TyKind` on every call to `intern_ty(...)` when computing flags. This saves several function calls and branches. As such I also had to create separate `flags()` functions to get the flags for a `TyKind` so we don't have to do a match on the kind. ### LLM usage; TLDR; I prototyped a PR as I knew a lot of the implementation would be boilerplate, ran perf to see if it was worth following up on, @lqd & @lcnr thought it looked promising. Hence I've now opened this PR which is my work borrowing parts from the prototype. **Longer version** The idea is mine and I discussed it with @lcnr before doing any work, we also decided using an LLM to explore if the idea was worth pursing seemed reasonable. I used an LLM to completely vibe code the [first commit of a prototype-y PR](1b6b590) to verify the idea, which I then reviewed, and subsequently [ran perf, things looked decent](#165136 (comment)). The other commits in that prototype PR were me, not an LLM, trying to effectively create the below idea; ```rust fn compute_flags<const K: ty::TyKind<'tcx>() { const match K.kind() { // } } ``` Which I subsequently abandoned as I couldn't get it to work even when turning on a bunch of experimental features. I appreciate that might be me doing things wrong. I tried this as to me this idea seems to scream for compile-time evaluation as we can know the `TyKind` at compile time. This PR has been written by me borrowing bits from my original LLM/James collaborative prototype. </details> r? @nnethercote
2 parents 6c587fd + e2cd888 commit e2867c9

3 files changed

Lines changed: 421 additions & 193 deletions

File tree

‎compiler/rustc_middle/src/ty/context.rs‎

Lines changed: 255 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ use rustc_structures::{CrateType, Limit};
4848
use rustc_type_ir::TyKind::*;
4949
pub use rustc_type_ir::lift::Lift;
5050
use rustc_type_ir::{
51-
CollectAndApply, IncludeSizedImplicitBounds, PlaceholderType, WithCachedTypeInfo, elaborate,
52-
search_graph,
51+
CollectAndApply, IncludeSizedImplicitBounds, PlaceholderType, TypeFlags, WithCachedTypeInfo,
52+
elaborate, search_graph,
5353
};
5454
use tracing::{debug, instrument};
5555

@@ -75,10 +75,10 @@ use crate::traits::solve::{
7575
use crate::ty::predicate::ExistentialPredicateStableCmpExt as _;
7676
use crate::ty::{
7777
self, AdtDef, AdtDefData, AdtKind, Binder, CanonicalizerState, Clause, ClausePolarity, Clauses,
78-
Const, ConstKind, FnSigKind, GenericArg, GenericArgsUnsized, GenericParamDefKind, List,
79-
ListWithCachedTypeInfo, ParamConst, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig,
80-
Predicate, PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind,
81-
TyVid, ValTree, ValTreeKind, Visibility,
78+
Const, ConstKind, FlagComputation, FnSigKind, GenericArg, GenericArgsUnsized,
79+
GenericParamDefKind, List, ListWithCachedTypeInfo, ParamConst, Pattern, PatternKind,
80+
PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, Region, RegionKind, ReprOptions,
81+
TraitObjectVisitor, Ty, TyKind, TyVid, ValTree, ValTreeKind, Visibility,
8282
};
8383

8484
impl<'tcx> rustc_type_ir::inherent::DefId<TyCtxt<'tcx>> for DefId {
@@ -216,24 +216,6 @@ impl<'tcx> CtxtInterners<'tcx> {
216216
}
217217
}
218218

219-
/// Interns a type. (Use `mk_*` functions instead, where possible.)
220-
#[allow(rustc::usage_of_ty_tykind)]
221-
#[inline(never)]
222-
fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> {
223-
Ty(Interned::new_unchecked(
224-
self.type_
225-
.intern(kind, |kind| {
226-
let flags = ty::FlagComputation::<TyCtxt<'tcx>>::for_kind(&kind);
227-
InternedInSet(self.arena.alloc(WithCachedTypeInfo {
228-
internee: kind,
229-
flags: flags.flags,
230-
outer_exclusive_binder: flags.outer_exclusive_binder,
231-
}))
232-
})
233-
.0,
234-
))
235-
}
236-
237219
/// Interns a const. (Use `mk_*` functions instead, where possible.)
238220
#[allow(rustc::usage_of_ty_tykind)]
239221
#[inline(never)]
@@ -286,6 +268,196 @@ impl<'tcx> CtxtInterners<'tcx> {
286268
.0
287269
}
288270
}
271+
272+
#[allow(rustc::usage_of_ty_tykind)]
273+
#[inline(always)]
274+
fn intern_ty(
275+
&self,
276+
kind: ty::TyKind<'tcx>,
277+
create_flags: impl FnOnce() -> FlagComputation<TyCtxt<'tcx>>,
278+
) -> Ty<'tcx> {
279+
Ty(Interned::new_unchecked(
280+
self.type_
281+
.intern(kind, |_| {
282+
let flags = create_flags();
283+
InternedInSet(self.arena.alloc(WithCachedTypeInfo {
284+
internee: kind,
285+
flags: flags.flags,
286+
outer_exclusive_binder: flags.outer_exclusive_binder,
287+
}))
288+
})
289+
.0,
290+
))
291+
}
292+
293+
#[inline(never)]
294+
fn intern_with_empty_flags(&self, kind: ty::TyKind<'tcx>) -> Ty<'tcx> {
295+
self.intern_ty(kind, || FlagComputation::for_flags(TypeFlags::empty()))
296+
}
297+
298+
#[inline(never)]
299+
pub(super) fn intern_pat(&self, base: Ty<'tcx>, pat: Pattern<'tcx>) -> Ty<'tcx> {
300+
self.intern_ty(Pat(base, pat), || FlagComputation::for_pat(base, pat))
301+
}
302+
303+
#[inline(never)]
304+
pub(super) fn intern_coroutine_witness(
305+
&self,
306+
def_id: DefId,
307+
args: ty::GenericArgs<'tcx>,
308+
) -> Ty<'tcx> {
309+
self.intern_ty(ty::CoroutineWitness(def_id, args), || FlagComputation::for_args(args))
310+
}
311+
312+
#[inline(never)]
313+
pub(super) fn intern_infer(&self, infer: ty::InferTy) -> Ty<'tcx> {
314+
self.intern_ty(Infer(infer), || FlagComputation::for_infer(infer))
315+
}
316+
317+
#[inline(never)]
318+
pub(super) fn intern_error(&self, error: rustc_errors::ErrorGuaranteed) -> Ty<'tcx> {
319+
self.intern_ty(Error(error), || {
320+
FlagComputation::for_flags(ty::TypeFlags::HAS_NON_REGION_ERROR)
321+
})
322+
}
323+
324+
#[inline(never)]
325+
pub(super) fn intern_adt(&self, def: AdtDef<'tcx>, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> {
326+
self.intern_ty(Adt(def, args), || FlagComputation::for_args(args))
327+
}
328+
329+
#[inline(never)]
330+
pub(super) fn intern_foreign(&self, def_id: DefId) -> Ty<'tcx> {
331+
self.intern_ty(Foreign(def_id), || FlagComputation::for_flags(TypeFlags::empty()))
332+
}
333+
334+
#[inline(never)]
335+
pub(super) fn intern_array(&self, element: Ty<'tcx>, len: Const<'tcx>) -> Ty<'tcx> {
336+
self.intern_ty(Array(element, len), || FlagComputation::for_array(element, len))
337+
}
338+
339+
#[inline(never)]
340+
pub(super) fn intern_slice(&self, element: Ty<'tcx>) -> Ty<'tcx> {
341+
self.intern_ty(Slice(element), || FlagComputation::for_ty(element))
342+
}
343+
344+
#[inline(never)]
345+
pub(super) fn intern_raw_ptr(
346+
&self,
347+
pointee: Ty<'tcx>,
348+
mutability: hir::Mutability,
349+
) -> Ty<'tcx> {
350+
self.intern_ty(RawPtr(pointee, mutability), || FlagComputation::for_ty(pointee))
351+
}
352+
353+
#[inline(never)]
354+
pub(super) fn intern_ref(
355+
&self,
356+
region: Region<'tcx>,
357+
pointee: Ty<'tcx>,
358+
mutability: hir::Mutability,
359+
) -> Ty<'tcx> {
360+
self.intern_ty(Ref(region, pointee, mutability), || {
361+
FlagComputation::for_ref(region, pointee)
362+
})
363+
}
364+
365+
#[inline(never)]
366+
pub(super) fn intern_fn_def(
367+
&self,
368+
def_id: DefId,
369+
args: Binder<'tcx, ty::GenericArgs<'tcx>>,
370+
) -> Ty<'tcx> {
371+
self.intern_ty(FnDef(def_id, args), || FlagComputation::for_fn_def(args))
372+
}
373+
374+
#[inline(never)]
375+
pub(super) fn intern_fn_ptr(
376+
&self,
377+
sig_tys: Binder<'tcx, ty::FnSigTys<TyCtxt<'tcx>>>,
378+
header: ty::FnHeader<TyCtxt<'tcx>>,
379+
) -> Ty<'tcx> {
380+
self.intern_ty(FnPtr(sig_tys, header), || FlagComputation::for_fn_ptr(sig_tys))
381+
}
382+
383+
#[inline(never)]
384+
pub(super) fn intern_unsafe_binder(
385+
&self,
386+
bound_ty: ty::UnsafeBinderInner<TyCtxt<'tcx>>,
387+
) -> Ty<'tcx> {
388+
self.intern_ty(UnsafeBinder(bound_ty), || FlagComputation::for_unsafe_binder(bound_ty))
389+
}
390+
391+
#[inline(never)]
392+
pub(super) fn intern_dynamic(
393+
&self,
394+
predicates: &'tcx List<PolyExistentialPredicate<'tcx>>,
395+
region: Region<'tcx>,
396+
) -> Ty<'tcx> {
397+
self.intern_ty(Dynamic(predicates, region), || {
398+
FlagComputation::for_dynamic(predicates, region)
399+
})
400+
}
401+
402+
#[inline(never)]
403+
pub(super) fn intern_closure(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> {
404+
self.intern_ty(Closure(def_id, args), || FlagComputation::for_args(args))
405+
}
406+
407+
#[inline(never)]
408+
pub(super) fn intern_coroutine_closure(
409+
&self,
410+
def_id: DefId,
411+
args: ty::GenericArgs<'tcx>,
412+
) -> Ty<'tcx> {
413+
self.intern_ty(CoroutineClosure(def_id, args), || FlagComputation::for_args(args))
414+
}
415+
416+
#[inline(never)]
417+
pub(super) fn intern_coroutine(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Ty<'tcx> {
418+
self.intern_ty(Coroutine(def_id, args), || FlagComputation::for_coroutine(args))
419+
}
420+
421+
#[inline(never)]
422+
pub(super) fn intern_tuple(&self, types: &'tcx List<Ty<'tcx>>) -> Ty<'tcx> {
423+
self.intern_ty(Tuple(types), || FlagComputation::for_tys(types))
424+
}
425+
426+
#[inline(never)]
427+
pub(super) fn intern_alias(&self, is_rigid: ty::IsRigid, alias: ty::AliasTy<'tcx>) -> Ty<'tcx> {
428+
self.intern_ty(Alias(is_rigid, alias), || FlagComputation::for_alias(is_rigid, alias))
429+
}
430+
431+
#[inline(never)]
432+
pub(super) fn intern_param(&self, param: ty::ParamTy) -> Ty<'tcx> {
433+
self.intern_ty(Param(param), || FlagComputation::for_flags(ty::TypeFlags::HAS_TY_PARAM))
434+
}
435+
436+
#[inline(never)]
437+
pub(super) fn intern_bound(
438+
&self,
439+
index: ty::BoundVarIndexKind,
440+
bound_ty: ty::BoundTy<'tcx>,
441+
) -> Ty<'tcx> {
442+
self.intern_ty(Bound(index, bound_ty), || FlagComputation::for_bound(index))
443+
}
444+
445+
#[inline(never)]
446+
pub(super) fn intern_placeholder(&self, placeholder: ty::PlaceholderType<'tcx>) -> Ty<'tcx> {
447+
self.intern_ty(Placeholder(placeholder), || {
448+
FlagComputation::for_flags(ty::TypeFlags::HAS_TY_PLACEHOLDER)
449+
})
450+
}
451+
452+
#[inline(never)]
453+
pub(super) fn intern_view(
454+
&self,
455+
def: ty::AdtDef<'tcx>,
456+
args: ty::GenericArgs<'tcx>,
457+
fields: Ty<'tcx>,
458+
) -> Ty<'tcx> {
459+
self.intern_ty(View(def, args, fields), || FlagComputation::for_view(args, fields))
460+
}
289461
}
290462

291463
// For these preinterned values, an alternative would be to have
@@ -425,53 +597,55 @@ pub struct CommonConsts<'tcx> {
425597

426598
impl<'tcx> CommonTypes<'tcx> {
427599
fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> {
428-
let mk = |ty| interners.intern_ty(ty);
600+
let mk = |ty| interners.intern_with_empty_flags(ty);
429601

430602
let infer_ty_vars = (0..NUM_PREINTERNED_INFER_TY_VARS)
431-
.map(|n| mk(Infer(ty::TyVar(TyVid::from(n)))))
603+
.map(|n| interners.intern_infer(ty::TyVar(TyVid::from(n))))
432604
.collect();
433-
let infer_fresh_tys: Vec<_> =
434-
(0..NUM_PREINTERNED_INFER_FRESH_TYS).map(|n| mk(Infer(ty::FreshTy(n)))).collect();
605+
let infer_fresh_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_TYS)
606+
.map(|n| interners.intern_infer(ty::FreshTy(n)))
607+
.collect();
608+
435609
let infer_fresh_int_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_INT_TYS)
436-
.map(|n| mk(Infer(ty::FreshIntTy(n))))
610+
.map(|n| interners.intern_infer(ty::FreshIntTy(n)))
437611
.collect();
438612
let infer_fresh_float_tys: Vec<_> = (0..NUM_PREINTERNED_INFER_FRESH_FLOAT_TYS)
439-
.map(|n| mk(Infer(ty::FreshFloatTy(n))))
613+
.map(|n| interners.intern_infer(ty::FreshFloatTy(n)))
440614
.collect();
441615

442616
let bound_bound_anons = (0..NUM_PREINTERNED_BOUND_BOUND_ANONS_I)
443617
.map(|i| {
444618
(0..NUM_PREINTERNED_BOUND_BOUND_ANONS_V)
445619
.map(|v| {
446-
mk(ty::Bound(
620+
interners.intern_bound(
447621
ty::BoundVarIndexKind::Bound(ty::DebruijnIndex::from(i)),
448622
ty::BoundTy { var: ty::BoundVar::from(v), kind: ty::BoundTyKind::Anon },
449-
))
623+
)
450624
})
451625
.collect()
452626
})
453627
.collect();
454628

455629
let bound_canonical_anons = (0..NUM_PREINTERNED_BOUND_CANONICAL_ANONS)
456630
.map(|v| {
457-
mk(ty::Bound(
631+
interners.intern_bound(
458632
ty::BoundVarIndexKind::Canonical,
459633
ty::BoundTy { var: ty::BoundVar::from(v), kind: ty::BoundTyKind::Anon },
460-
))
634+
)
461635
})
462636
.collect();
463637

464638
let placeholder_root_anons = (0..NUM_PREINTERNED_PLACEHOLDER_ROOT_ANONS)
465639
.map(|v| {
466-
mk(ty::Placeholder(PlaceholderType::new_anon(
640+
interners.intern_placeholder(PlaceholderType::new_anon(
467641
ty::UniverseIndex::ROOT,
468642
ty::BoundVar::from(v),
469-
)))
643+
))
470644
})
471645
.collect();
472646

473647
CommonTypes {
474-
unit: mk(Tuple(List::empty())),
648+
unit: interners.intern_tuple(List::empty()),
475649
bool: mk(Bool),
476650
char: mk(Char),
477651
never: mk(Never),
@@ -492,7 +666,8 @@ impl<'tcx> CommonTypes<'tcx> {
492666
f64: mk(Float(ty::FloatTy::F64)),
493667
f128: mk(Float(ty::FloatTy::F128)),
494668
str_: mk(Str),
495-
self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })),
669+
670+
self_param: interners.intern_param(ty::ParamTy { index: 0, name: kw::SelfUpper }),
496671

497672
trait_object_dummy_self: infer_fresh_tys[0],
498673

@@ -772,7 +947,7 @@ pub struct GlobalCtxt<'tcx> {
772947
pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
773948
pub hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
774949

775-
interners: CtxtInterners<'tcx>,
950+
pub(super) interners: CtxtInterners<'tcx>,
776951

777952
pub sess: &'tcx Session,
778953
crate_types: Vec<CrateType>,
@@ -2470,11 +2645,50 @@ impl<'tcx> TyCtxt<'tcx> {
24702645
self.interners.intern_const(kind)
24712646
}
24722647

2473-
// Avoid this in favour of more specific `Ty::new_*` methods, where possible.
2648+
// Avoid this in favour of more specific `Ty::new_*` methods where possible.
2649+
// They will be faster because they avoid this match statement.
2650+
// FIXME(Jamesbarford): Minimise usage.
24742651
#[allow(rustc::usage_of_ty_tykind)]
24752652
#[inline]
24762653
pub fn mk_ty_from_kind(self, st: TyKind<'tcx>) -> Ty<'tcx> {
2477-
self.interners.intern_ty(st)
2654+
match st {
2655+
ty::Bool => self.interners.intern_with_empty_flags(ty::Bool),
2656+
ty::Char => self.interners.intern_with_empty_flags(ty::Char),
2657+
ty::Int(int) => self.interners.intern_with_empty_flags(ty::Int(int)),
2658+
ty::Uint(uint) => self.interners.intern_with_empty_flags(ty::Uint(uint)),
2659+
ty::Float(float) => self.interners.intern_with_empty_flags(ty::Float(float)),
2660+
ty::Adt(def, args) => self.interners.intern_adt(def, args),
2661+
ty::Foreign(def_id) => self.interners.intern_foreign(def_id),
2662+
ty::Str => self.interners.intern_with_empty_flags(ty::Str),
2663+
ty::Array(element, len) => self.interners.intern_array(element, len),
2664+
ty::Pat(base, pat) => self.interners.intern_pat(base, pat),
2665+
ty::Slice(element) => self.interners.intern_slice(element),
2666+
ty::RawPtr(pointee, mutability) => self.interners.intern_raw_ptr(pointee, mutability),
2667+
ty::Ref(region, pointee, mutability) => {
2668+
self.interners.intern_ref(region, pointee, mutability)
2669+
}
2670+
ty::FnDef(def_id, args) => self.interners.intern_fn_def(def_id, args),
2671+
ty::FnPtr(sig_tys, header) => self.interners.intern_fn_ptr(sig_tys, header),
2672+
ty::UnsafeBinder(bound_ty) => self.interners.intern_unsafe_binder(bound_ty),
2673+
ty::Dynamic(predicates, region) => self.interners.intern_dynamic(predicates, region),
2674+
ty::Closure(def_id, args) => self.interners.intern_closure(def_id, args),
2675+
ty::CoroutineClosure(def_id, args) => {
2676+
self.interners.intern_coroutine_closure(def_id, args)
2677+
}
2678+
ty::Coroutine(def_id, args) => self.interners.intern_coroutine(def_id, args),
2679+
ty::CoroutineWitness(def_id, args) => {
2680+
self.interners.intern_coroutine_witness(def_id, args)
2681+
}
2682+
ty::Never => self.interners.intern_with_empty_flags(ty::Never),
2683+
ty::Tuple(types) => self.interners.intern_tuple(types),
2684+
ty::Alias(is_rigid, alias) => self.interners.intern_alias(is_rigid, alias),
2685+
ty::Param(param) => self.interners.intern_param(param),
2686+
ty::Bound(index, bound_ty) => self.interners.intern_bound(index, bound_ty),
2687+
ty::Placeholder(placeholder) => self.interners.intern_placeholder(placeholder),
2688+
ty::Infer(infer) => self.interners.intern_infer(infer),
2689+
ty::Error(error) => self.interners.intern_error(error),
2690+
ty::View(def, args, fields) => self.interners.intern_view(def, args, fields),
2691+
}
24782692
}
24792693

24802694
pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> {

0 commit comments

Comments
 (0)