Skip to content

Commit dbc40a5

Browse files
committed
Auto merge of rust-lang#130821 - lcnr:nalgebra-hang-2, r=<try>
add caching to most type folders Fixes the new minimization of the hang in nalgebra and nalgebra itself :3 this is a bit iffy, especially the cache in `TypeRelating`. I believe all the caches are correct, but it definitely adds some non-local complexity in places. The first commit removes region uniquification, reintroducing the ICE from rust-lang/trait-system-refactor-initiative#27. This does not affect coherence and I would like to fix this by introducing OR-region constraints r? `@compiler-errors`
2 parents e9df22f + 908178a commit dbc40a5

File tree

12 files changed

+433
-133
lines changed

12 files changed

+433
-133
lines changed

compiler/rustc_infer/src/infer/relate/combine.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,15 @@ use crate::traits::{Obligation, PredicateObligation};
3636
#[derive(Clone)]
3737
pub struct CombineFields<'infcx, 'tcx> {
3838
pub infcx: &'infcx InferCtxt<'tcx>,
39+
// Immutable fields
3940
pub trace: TypeTrace<'tcx>,
4041
pub param_env: ty::ParamEnv<'tcx>,
41-
pub goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
4242
pub define_opaque_types: DefineOpaqueTypes,
43+
// Mutable fields
44+
//
45+
// Adding any additional field likely requires
46+
// changes to the cache of `TypeRelating`.
47+
pub goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
4348
}
4449

4550
impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {

compiler/rustc_infer/src/infer/relate/type_relating.rs

+40-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use rustc_middle::ty::relate::{
44
};
55
use rustc_middle::ty::{self, Ty, TyCtxt, TyVar};
66
use rustc_span::Span;
7+
use rustc_type_ir::data_structures::DelayedSet;
78
use tracing::{debug, instrument};
89

910
use super::combine::CombineFields;
@@ -13,9 +14,36 @@ use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin};
1314

1415
/// Enforce that `a` is equal to or a subtype of `b`.
1516
pub struct TypeRelating<'combine, 'a, 'tcx> {
17+
// Partially mutable.
1618
fields: &'combine mut CombineFields<'a, 'tcx>,
19+
20+
// Immutable fields.
1721
structurally_relate_aliases: StructurallyRelateAliases,
1822
ambient_variance: ty::Variance,
23+
24+
/// The cache has only tracks the `ambient_variance` as its the
25+
/// only field which is mutable and which meaningfully changes
26+
/// the result when relating types.
27+
///
28+
/// The cache does not track whether the state of the
29+
/// `InferCtxt` has been changed or whether we've added any
30+
/// obligations to `self.fields.goals`. Whether a goal is added
31+
/// once or multiple times is not really meaningful.
32+
///
33+
/// Changes in the inference state may delay some type inference to
34+
/// the next fulfillment loop. Given that this look is already
35+
/// necessary, this is also not a meaningful change, consider
36+
/// the following three relations:
37+
/// ```text
38+
/// Vec<?0> sub Vec<?1>
39+
/// ?0 eq u32
40+
/// Vec<?0> sub Vec<?1>
41+
/// ```
42+
/// Without a cache, `Vec<?0> sub Vec<?1>` would eagerly constrain
43+
/// `?1` to `u32`. When using the cache entry from the first time
44+
/// we've related these types, this only happens when later proving
45+
/// the `Subtype(?0, ?1)` goal from the first relation.
46+
cache: DelayedSet<(ty::Variance, Ty<'tcx>, Ty<'tcx>)>,
1947
}
2048

2149
impl<'combine, 'infcx, 'tcx> TypeRelating<'combine, 'infcx, 'tcx> {
@@ -24,7 +52,12 @@ impl<'combine, 'infcx, 'tcx> TypeRelating<'combine, 'infcx, 'tcx> {
2452
structurally_relate_aliases: StructurallyRelateAliases,
2553
ambient_variance: ty::Variance,
2654
) -> TypeRelating<'combine, 'infcx, 'tcx> {
27-
TypeRelating { fields: f, structurally_relate_aliases, ambient_variance }
55+
TypeRelating {
56+
fields: f,
57+
structurally_relate_aliases,
58+
ambient_variance,
59+
cache: Default::default(),
60+
}
2861
}
2962
}
3063

@@ -78,6 +111,10 @@ impl<'tcx> TypeRelation<TyCtxt<'tcx>> for TypeRelating<'_, '_, 'tcx> {
78111
let a = infcx.shallow_resolve(a);
79112
let b = infcx.shallow_resolve(b);
80113

114+
if self.cache.contains(&(self.ambient_variance, a, b)) {
115+
return Ok(a);
116+
}
117+
81118
match (a.kind(), b.kind()) {
82119
(&ty::Infer(TyVar(a_id)), &ty::Infer(TyVar(b_id))) => {
83120
match self.ambient_variance {
@@ -160,6 +197,8 @@ impl<'tcx> TypeRelation<TyCtxt<'tcx>> for TypeRelating<'_, '_, 'tcx> {
160197
}
161198
}
162199

200+
assert!(self.cache.insert((self.ambient_variance, a, b)));
201+
163202
Ok(a)
164203
}
165204

compiler/rustc_infer/src/infer/resolve.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use rustc_middle::bug;
22
use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFolder, TypeSuperFoldable};
33
use rustc_middle::ty::visit::TypeVisitableExt;
44
use rustc_middle::ty::{self, Const, InferConst, Ty, TyCtxt, TypeFoldable};
5+
use rustc_type_ir::data_structures::DelayedMap;
56

67
use super::{FixupError, FixupResult, InferCtxt};
78

@@ -15,12 +16,15 @@ use super::{FixupError, FixupResult, InferCtxt};
1516
/// points for correctness.
1617
pub struct OpportunisticVarResolver<'a, 'tcx> {
1718
infcx: &'a InferCtxt<'tcx>,
19+
/// We're able to use a cache here as the folder does
20+
/// not have any mutable state.
21+
cache: DelayedMap<Ty<'tcx>, Ty<'tcx>>,
1822
}
1923

2024
impl<'a, 'tcx> OpportunisticVarResolver<'a, 'tcx> {
2125
#[inline]
2226
pub fn new(infcx: &'a InferCtxt<'tcx>) -> Self {
23-
OpportunisticVarResolver { infcx }
27+
OpportunisticVarResolver { infcx, cache: Default::default() }
2428
}
2529
}
2630

@@ -33,9 +37,13 @@ impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for OpportunisticVarResolver<'a, 'tcx> {
3337
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
3438
if !t.has_non_region_infer() {
3539
t // micro-optimize -- if there is nothing in this type that this fold affects...
40+
} else if let Some(&ty) = self.cache.get(&t) {
41+
return ty;
3642
} else {
37-
let t = self.infcx.shallow_resolve(t);
38-
t.super_fold_with(self)
43+
let shallow = self.infcx.shallow_resolve(t);
44+
let res = shallow.super_fold_with(self);
45+
assert!(self.cache.insert(t, res));
46+
res
3947
}
4048
}
4149

compiler/rustc_middle/src/ty/fold.rs

+22-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use rustc_data_structures::fx::FxIndexMap;
22
use rustc_hir::def_id::DefId;
3+
use rustc_type_ir::data_structures::DelayedMap;
34
pub use rustc_type_ir::fold::{
45
FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable, shift_region, shift_vars,
56
};
@@ -131,12 +132,19 @@ impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for RegionFolder<'a, 'tcx> {
131132
///////////////////////////////////////////////////////////////////////////
132133
// Bound vars replacer
133134

135+
/// A delegate used when instantiating bound vars.
136+
///
137+
/// Any implementation must make sure that each bound variable always
138+
/// gets mapped to the same result. `BoundVarReplacer` caches by using
139+
/// a `DelayedMap` which does not cache the first few types it encounters.
134140
pub trait BoundVarReplacerDelegate<'tcx> {
135141
fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx>;
136142
fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx>;
137143
fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx>;
138144
}
139145

146+
/// A simple delegate taking 3 mutable functions. It must not be observable
147+
/// whether a function is used once or multiple times.
140148
pub struct FnMutDelegate<'a, 'tcx> {
141149
pub regions: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a),
142150
pub types: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a),
@@ -164,11 +172,15 @@ struct BoundVarReplacer<'tcx, D> {
164172
current_index: ty::DebruijnIndex,
165173

166174
delegate: D,
175+
176+
/// This cache only tracks the `DebruijnIndex` and assumes that it does not matter
177+
/// for the delegate whether its methods get used a single time or multiple times.
178+
cache: DelayedMap<(ty::DebruijnIndex, Ty<'tcx>), Ty<'tcx>>,
167179
}
168180

169181
impl<'tcx, D: BoundVarReplacerDelegate<'tcx>> BoundVarReplacer<'tcx, D> {
170182
fn new(tcx: TyCtxt<'tcx>, delegate: D) -> Self {
171-
BoundVarReplacer { tcx, current_index: ty::INNERMOST, delegate }
183+
BoundVarReplacer { tcx, current_index: ty::INNERMOST, delegate, cache: Default::default() }
172184
}
173185
}
174186

@@ -197,7 +209,15 @@ where
197209
debug_assert!(!ty.has_vars_bound_above(ty::INNERMOST));
198210
ty::fold::shift_vars(self.tcx, ty, self.current_index.as_u32())
199211
}
200-
_ if t.has_vars_bound_at_or_above(self.current_index) => t.super_fold_with(self),
212+
_ if t.has_vars_bound_at_or_above(self.current_index) => {
213+
if let Some(&ty) = self.cache.get(&(self.current_index, t)) {
214+
return ty;
215+
}
216+
217+
let res = t.super_fold_with(self);
218+
assert!(self.cache.insert((self.current_index, t), res));
219+
res
220+
}
201221
_ => t,
202222
}
203223
}

0 commit comments

Comments
 (0)