Skip to content

Commit 713d917

Browse files
committed
Auto merge of #26326 - nikomatsakis:optimize-fulfillment-cache-in-tcx, r=pcwalton
When we successfully resolve a trait reference with no type/lifetime parameters, like `i32: Foo` or `Box<u32>: Sized`, this is in fact globally true. This patch adds a simple global to the tcx to cache such cases. The main advantage of this is really about caching things like `Box<Vec<Foo>>: Sized`. It also points to the need to revamp our caching infrastructure -- the current caches make selection cost cheaper, but we still wind up paying a high cost in the confirmation process, and in particular unrolling out dependent obligations. Moreover, we should probably do caching more uniformly and with a key that takes the where-clauses into account. But that's for later. For me, this shows up as a reasonably nice win (20%) on Servo's script crate (when built in dev mode). This is not as big as my initial measurements suggested, I think because I was building my rustc with more debugging enabled at the time. I've not yet done follow-up profiling and so forth to see where the new hot spots are. Bootstrap times seem to be largely unaffected. cc @pcwalton This is technically a [breaking-change] in that functions with unsatisfiable where-clauses may now yield errors where before they may have been accepted. Even before, these functions could never have been *called* by actual code. In the future, such functions will probably become illegal altogether, but in this commit they are still accepted, so long as they do not rely on the unsatisfiable where-clauses. As before, the functions still cannot be called in any case.
2 parents 8af39ce + 957935a commit 713d917

19 files changed

+253
-60
lines changed

src/librustc/middle/check_const.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ impl<'a, 'tcx> CheckCrateVisitor<'a, 'tcx> {
285285
fn check_static_type(&self, e: &ast::Expr) {
286286
let ty = ty::node_id_to_type(self.tcx, e.id);
287287
let infcx = infer::new_infer_ctxt(self.tcx);
288-
let mut fulfill_cx = traits::FulfillmentContext::new();
288+
let mut fulfill_cx = traits::FulfillmentContext::new(false);
289289
let cause = traits::ObligationCause::new(e.span, e.id, traits::SharedStatic);
290290
fulfill_cx.register_builtin_bound(&infcx, ty, ty::BoundSync, cause);
291291
let env = ty::empty_parameter_environment(self.tcx);

src/librustc/middle/traits/fulfill.rs

+68-4
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ use super::select::SelectionContext;
2828
use super::Unimplemented;
2929
use super::util::predicate_for_builtin_bound;
3030

31+
pub struct FulfilledPredicates<'tcx> {
32+
set: HashSet<ty::Predicate<'tcx>>
33+
}
34+
3135
/// The fulfillment context is used to drive trait resolution. It
3236
/// consists of a list of obligations that must be (eventually)
3337
/// satisfied. The job is to track which are satisfied, which yielded
@@ -44,7 +48,7 @@ pub struct FulfillmentContext<'tcx> {
4448
// than the `SelectionCache`: it avoids duplicate errors and
4549
// permits recursive obligations, which are often generated from
4650
// traits like `Send` et al.
47-
duplicate_set: HashSet<ty::Predicate<'tcx>>,
51+
duplicate_set: FulfilledPredicates<'tcx>,
4852

4953
// A list of all obligations that have been registered with this
5054
// fulfillment context.
@@ -80,6 +84,8 @@ pub struct FulfillmentContext<'tcx> {
8084
// obligations (otherwise, it's easy to fail to walk to a
8185
// particular node-id).
8286
region_obligations: NodeMap<Vec<RegionObligation<'tcx>>>,
87+
88+
errors_will_be_reported: bool,
8389
}
8490

8591
#[derive(Clone)]
@@ -90,12 +96,30 @@ pub struct RegionObligation<'tcx> {
9096
}
9197

9298
impl<'tcx> FulfillmentContext<'tcx> {
93-
pub fn new() -> FulfillmentContext<'tcx> {
99+
/// Creates a new fulfillment context.
100+
///
101+
/// `errors_will_be_reported` indicates whether ALL errors that
102+
/// are generated by this fulfillment context will be reported to
103+
/// the end user. This is used to inform caching, because it
104+
/// allows us to conclude that traits that resolve successfully
105+
/// will in fact always resolve successfully (in particular, it
106+
/// guarantees that if some dependent obligation encounters a
107+
/// problem, compilation will be aborted). If you're not sure of
108+
/// the right value here, pass `false`, as that is the more
109+
/// conservative option.
110+
///
111+
/// FIXME -- a better option would be to hold back on modifying
112+
/// the global cache until we know that all dependent obligations
113+
/// are also satisfied. In that case, we could actually remove
114+
/// this boolean flag, and we'd also avoid the problem of squelching
115+
/// duplicate errors that occur across fns.
116+
pub fn new(errors_will_be_reported: bool) -> FulfillmentContext<'tcx> {
94117
FulfillmentContext {
95-
duplicate_set: HashSet::new(),
118+
duplicate_set: FulfilledPredicates::new(),
96119
predicates: Vec::new(),
97120
attempted_mark: 0,
98121
region_obligations: NodeMap(),
122+
errors_will_be_reported: errors_will_be_reported,
99123
}
100124
}
101125

@@ -165,7 +189,7 @@ impl<'tcx> FulfillmentContext<'tcx> {
165189

166190
assert!(!obligation.has_escaping_regions());
167191

168-
if !self.duplicate_set.insert(obligation.predicate.clone()) {
192+
if self.is_duplicate_or_add(infcx.tcx, &obligation.predicate) {
169193
debug!("register_predicate({}) -- already seen, skip", obligation.repr(infcx.tcx));
170194
return;
171195
}
@@ -231,6 +255,28 @@ impl<'tcx> FulfillmentContext<'tcx> {
231255
&self.predicates
232256
}
233257

258+
fn is_duplicate_or_add(&mut self, tcx: &ty::ctxt<'tcx>,
259+
predicate: &ty::Predicate<'tcx>)
260+
-> bool {
261+
// This is a kind of dirty hack to allow us to avoid "rederiving"
262+
// things that we have already proven in other methods.
263+
//
264+
// The idea is that any predicate that doesn't involve type
265+
// parameters and which only involves the 'static region (and
266+
// no other regions) is universally solvable, since impls are global.
267+
//
268+
// This is particularly important since even if we have a
269+
// cache hit in the selection context, we still wind up
270+
// evaluating the 'nested obligations'. This cache lets us
271+
// skip those.
272+
273+
if self.errors_will_be_reported && predicate.is_global() {
274+
tcx.fulfilled_predicates.borrow_mut().is_duplicate_or_add(predicate)
275+
} else {
276+
self.duplicate_set.is_duplicate_or_add(predicate)
277+
}
278+
}
279+
234280
/// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it
235281
/// only attempts to select obligations that haven't been seen before.
236282
fn select<'a>(&mut self,
@@ -442,3 +488,21 @@ fn register_region_obligation<'tcx>(tcx: &ty::ctxt<'tcx>,
442488
.push(region_obligation);
443489

444490
}
491+
492+
impl<'tcx> FulfilledPredicates<'tcx> {
493+
pub fn new() -> FulfilledPredicates<'tcx> {
494+
FulfilledPredicates {
495+
set: HashSet::new()
496+
}
497+
}
498+
499+
pub fn is_duplicate(&self, p: &ty::Predicate<'tcx>) -> bool {
500+
self.set.contains(p)
501+
}
502+
503+
fn is_duplicate_or_add(&mut self, p: &ty::Predicate<'tcx>) -> bool {
504+
!self.set.insert(p.clone())
505+
}
506+
}
507+
508+

src/librustc/middle/traits/mod.rs

+25-10
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub use self::error_reporting::suggest_new_overflow_limit;
3232
pub use self::coherence::orphan_check;
3333
pub use self::coherence::overlapping_impls;
3434
pub use self::coherence::OrphanCheckErr;
35-
pub use self::fulfill::{FulfillmentContext, RegionObligation};
35+
pub use self::fulfill::{FulfillmentContext, FulfilledPredicates, RegionObligation};
3636
pub use self::project::MismatchedProjectionTypes;
3737
pub use self::project::normalize;
3838
pub use self::project::Normalized;
@@ -315,7 +315,7 @@ pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
315315
ty.repr(infcx.tcx),
316316
bound);
317317

318-
let mut fulfill_cx = FulfillmentContext::new();
318+
let mut fulfill_cx = FulfillmentContext::new(false);
319319

320320
// We can use a dummy node-id here because we won't pay any mind
321321
// to region obligations that arise (there shouldn't really be any
@@ -414,9 +414,27 @@ pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvi
414414
debug!("normalize_param_env_or_error(unnormalized_env={})",
415415
unnormalized_env.repr(tcx));
416416

417+
let predicates: Vec<_> =
418+
util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.clone())
419+
.filter(|p| !p.is_global()) // (*)
420+
.collect();
421+
422+
// (*) Any predicate like `i32: Trait<u32>` or whatever doesn't
423+
// need to be in the *environment* to be proven, so screen those
424+
// out. This is important for the soundness of inter-fn
425+
// caching. Note though that we should probably check that these
426+
// predicates hold at the point where the environment is
427+
// constructed, but I am not currently doing so out of laziness.
428+
// -nmatsakis
429+
430+
debug!("normalize_param_env_or_error: elaborated-predicates={}",
431+
predicates.repr(tcx));
432+
433+
let elaborated_env = unnormalized_env.with_caller_bounds(predicates);
434+
417435
let infcx = infer::new_infer_ctxt(tcx);
418-
let predicates = match fully_normalize(&infcx, &unnormalized_env, cause,
419-
&unnormalized_env.caller_bounds) {
436+
let predicates = match fully_normalize(&infcx, &elaborated_env, cause,
437+
&elaborated_env.caller_bounds) {
420438
Ok(predicates) => predicates,
421439
Err(errors) => {
422440
report_fulfillment_errors(&infcx, &errors);
@@ -438,14 +456,11 @@ pub fn normalize_param_env_or_error<'a,'tcx>(unnormalized_env: ty::ParameterEnvi
438456
// all things considered.
439457
let err_msg = fixup_err_to_string(fixup_err);
440458
tcx.sess.span_err(span, &err_msg);
441-
return unnormalized_env; // an unnormalized env is better than nothing
459+
return elaborated_env; // an unnormalized env is better than nothing
442460
}
443461
};
444462

445-
debug!("normalize_param_env_or_error: predicates={}",
446-
predicates.repr(tcx));
447-
448-
unnormalized_env.with_caller_bounds(predicates)
463+
elaborated_env.with_caller_bounds(predicates)
449464
}
450465

451466
pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
@@ -460,7 +475,7 @@ pub fn fully_normalize<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>,
460475
debug!("normalize_param_env(value={})", value.repr(tcx));
461476

462477
let mut selcx = &mut SelectionContext::new(infcx, closure_typer);
463-
let mut fulfill_cx = FulfillmentContext::new();
478+
let mut fulfill_cx = FulfillmentContext::new(false);
464479
let Normalized { value: normalized_value, obligations } =
465480
project::normalize(selcx, cause, value);
466481
debug!("normalize_param_env: normalized_value={} obligations={}",

src/librustc/middle/traits/project.rs

+12-8
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,7 @@ fn assemble_candidates_from_param_env<'cx,'tcx>(
535535
obligation_trait_ref: &ty::TraitRef<'tcx>,
536536
candidate_set: &mut ProjectionTyCandidateSet<'tcx>)
537537
{
538-
let env_predicates = selcx.param_env().caller_bounds.clone();
538+
let env_predicates = selcx.param_env().caller_bounds.iter().cloned();
539539
assemble_candidates_from_predicates(selcx, obligation, obligation_trait_ref,
540540
candidate_set, env_predicates);
541541
}
@@ -571,22 +571,25 @@ fn assemble_candidates_from_trait_def<'cx,'tcx>(
571571
// If so, extract what we know from the trait and try to come up with a good answer.
572572
let trait_predicates = ty::lookup_predicates(selcx.tcx(), trait_ref.def_id);
573573
let bounds = trait_predicates.instantiate(selcx.tcx(), trait_ref.substs);
574+
let bounds = elaborate_predicates(selcx.tcx(), bounds.predicates.into_vec());
574575
assemble_candidates_from_predicates(selcx, obligation, obligation_trait_ref,
575-
candidate_set, bounds.predicates.into_vec());
576+
candidate_set, bounds)
576577
}
577578

578-
fn assemble_candidates_from_predicates<'cx,'tcx>(
579+
fn assemble_candidates_from_predicates<'cx,'tcx,I>(
579580
selcx: &mut SelectionContext<'cx,'tcx>,
580581
obligation: &ProjectionTyObligation<'tcx>,
581582
obligation_trait_ref: &ty::TraitRef<'tcx>,
582583
candidate_set: &mut ProjectionTyCandidateSet<'tcx>,
583-
env_predicates: Vec<ty::Predicate<'tcx>>)
584+
env_predicates: I)
585+
where I: Iterator<Item=ty::Predicate<'tcx>>
584586
{
585-
debug!("assemble_candidates_from_predicates(obligation={}, env_predicates={})",
586-
obligation.repr(selcx.tcx()),
587-
env_predicates.repr(selcx.tcx()));
587+
debug!("assemble_candidates_from_predicates(obligation={})",
588+
obligation.repr(selcx.tcx()));
588589
let infcx = selcx.infcx();
589-
for predicate in elaborate_predicates(selcx.tcx(), env_predicates) {
590+
for predicate in env_predicates {
591+
debug!("assemble_candidates_from_predicates: predicate={}",
592+
predicate.repr(selcx.tcx()));
590593
match predicate {
591594
ty::Predicate::Projection(ref data) => {
592595
let same_name = data.item_name() == obligation.predicate.item_name;
@@ -641,6 +644,7 @@ fn assemble_candidates_from_object_type<'cx,'tcx>(
641644
let env_predicates = projection_bounds.iter()
642645
.map(|p| p.as_predicate())
643646
.collect();
647+
let env_predicates = elaborate_predicates(selcx.tcx(), env_predicates);
644648
assemble_candidates_from_predicates(selcx, obligation, obligation_trait_ref,
645649
candidate_set, env_predicates)
646650
}

src/librustc/middle/traits/select.rs

+11-7
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
435435
debug!("evaluate_predicate_recursively({})",
436436
obligation.repr(self.tcx()));
437437

438+
// Check the cache from the tcx of predicates that we know
439+
// have been proven elsewhere. This cache only contains
440+
// predicates that are global in scope and hence unaffected by
441+
// the current environment.
442+
if self.tcx().fulfilled_predicates.borrow().is_duplicate(&obligation.predicate) {
443+
return EvaluatedToOk;
444+
}
445+
438446
match obligation.predicate {
439447
ty::Predicate::Trait(ref t) => {
440448
assert!(!t.has_escaping_regions());
@@ -1075,14 +1083,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
10751083
debug!("assemble_candidates_from_caller_bounds({})",
10761084
stack.obligation.repr(self.tcx()));
10771085

1078-
let caller_trait_refs: Vec<_> =
1079-
self.param_env().caller_bounds.iter()
1080-
.filter_map(|o| o.to_opt_poly_trait_ref())
1081-
.collect();
1082-
10831086
let all_bounds =
1084-
util::transitive_bounds(
1085-
self.tcx(), &caller_trait_refs[..]);
1087+
self.param_env().caller_bounds
1088+
.iter()
1089+
.filter_map(|o| o.to_opt_poly_trait_ref());
10861090

10871091
let matching_bounds =
10881092
all_bounds.filter(

0 commit comments

Comments
 (0)