Skip to content

Commit 5171011

Browse files
Rollup merge of rust-lang#121089 - oli-obk:create_def_feed, r=petrochenkov
Remove `feed_local_def_id` best reviewed commit by commit Basically I returned `TyCtxtFeed` from `create_def` and then preserved that in the local caches based on rust-lang#121084 r? ```@petrochenkov```
2 parents 8d31644 + ef00fae commit 5171011

File tree

15 files changed

+181
-86
lines changed

15 files changed

+181
-86
lines changed

compiler/rustc_ast_lowering/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
427427
tcx.ensure_with_value().early_lint_checks(());
428428
tcx.ensure_with_value().debugger_visualizers(LOCAL_CRATE);
429429
tcx.ensure_with_value().get_lang_items(());
430-
let (mut resolver, krate) = tcx.resolver_for_lowering(()).steal();
430+
let (mut resolver, krate) = tcx.resolver_for_lowering().steal();
431431

432432
let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
433433
let mut owners = IndexVec::from_fn_n(

compiler/rustc_driver_impl/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,7 @@ fn run_compiler(
418418
}
419419

420420
// Make sure name resolution and macro expansion is run.
421-
queries.global_ctxt()?.enter(|tcx| tcx.resolver_for_lowering(()));
421+
queries.global_ctxt()?.enter(|tcx| tcx.resolver_for_lowering());
422422

423423
if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
424424
return early_exit();

compiler/rustc_driver_impl/src/pretty.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ impl<'tcx> PrintExtra<'tcx> {
229229
{
230230
match self {
231231
PrintExtra::AfterParsing { krate, .. } => f(krate),
232-
PrintExtra::NeedsAstMap { tcx } => f(&tcx.resolver_for_lowering(()).borrow().1),
232+
PrintExtra::NeedsAstMap { tcx } => f(&tcx.resolver_for_lowering().borrow().1),
233233
}
234234
}
235235

@@ -281,7 +281,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
281281
}
282282
AstTreeExpanded => {
283283
debug!("pretty-printing expanded AST");
284-
format!("{:#?}", ex.tcx().resolver_for_lowering(()).borrow().1)
284+
format!("{:#?}", ex.tcx().resolver_for_lowering().borrow().1)
285285
}
286286
Hir(s) => {
287287
debug!("pretty printing HIR {:?}", s);

compiler/rustc_interface/src/passes.rs

+10-8
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ fn configure_and_expand(
280280

281281
fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) {
282282
let sess = tcx.sess;
283-
let (resolver, krate) = &*tcx.resolver_for_lowering(()).borrow();
283+
let (resolver, krate) = &*tcx.resolver_for_lowering().borrow();
284284
let mut lint_buffer = resolver.lint_buffer.steal();
285285

286286
if sess.opts.unstable_opts.input_stats {
@@ -531,10 +531,10 @@ fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[P
531531
}
532532
}
533533

534-
fn resolver_for_lowering<'tcx>(
534+
fn resolver_for_lowering_raw<'tcx>(
535535
tcx: TyCtxt<'tcx>,
536536
(): (),
537-
) -> &'tcx Steal<(ty::ResolverAstLowering, Lrc<ast::Crate>)> {
537+
) -> (&'tcx Steal<(ty::ResolverAstLowering, Lrc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
538538
let arenas = Resolver::arenas();
539539
let _ = tcx.registered_tools(()); // Uses `crate_for_resolver`.
540540
let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal();
@@ -549,16 +549,15 @@ fn resolver_for_lowering<'tcx>(
549549
ast_lowering: untracked_resolver_for_lowering,
550550
} = resolver.into_outputs();
551551

552-
let feed = tcx.feed_unit_query();
553-
feed.resolutions(tcx.arena.alloc(untracked_resolutions));
554-
tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Lrc::new(krate))))
552+
let resolutions = tcx.arena.alloc(untracked_resolutions);
553+
(tcx.arena.alloc(Steal::new((untracked_resolver_for_lowering, Lrc::new(krate)))), resolutions)
555554
}
556555

557556
pub(crate) fn write_dep_info(tcx: TyCtxt<'_>) {
558557
// Make sure name resolution and macro expansion is run for
559558
// the side-effect of providing a complete set of all
560559
// accessed files and env vars.
561-
let _ = tcx.resolver_for_lowering(());
560+
let _ = tcx.resolver_for_lowering();
562561

563562
let sess = tcx.sess;
564563
let _timer = sess.timer("write_dep_info");
@@ -607,7 +606,10 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
607606
let providers = &mut Providers::default();
608607
providers.analysis = analysis;
609608
providers.hir_crate = rustc_ast_lowering::lower_to_hir;
610-
providers.resolver_for_lowering = resolver_for_lowering;
609+
providers.resolver_for_lowering_raw = resolver_for_lowering_raw;
610+
providers.stripped_cfg_items =
611+
|tcx, _| tcx.arena.alloc_from_iter(tcx.resolutions(()).stripped_cfg_items.steal());
612+
providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
611613
providers.early_lint_checks = early_lint_checks;
612614
proc_macro_decls::provide(providers);
613615
rustc_const_eval::provide(providers);

compiler/rustc_interface/src/queries.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ use rustc_codegen_ssa::CodegenResults;
88
use rustc_data_structures::steal::Steal;
99
use rustc_data_structures::svh::Svh;
1010
use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, OnceLock, WorkerLocal};
11-
use rustc_hir::def::DefKind;
12-
use rustc_hir::def_id::{StableCrateId, CRATE_DEF_ID, LOCAL_CRATE};
11+
use rustc_hir::def_id::{StableCrateId, LOCAL_CRATE};
1312
use rustc_hir::definitions::Definitions;
1413
use rustc_incremental::setup_dep_graph;
1514
use rustc_metadata::creader::CStore;
@@ -144,10 +143,8 @@ impl<'tcx> Queries<'tcx> {
144143
stable_crate_id,
145144
)) as _);
146145
let definitions = FreezeLock::new(Definitions::new(stable_crate_id));
147-
let source_span = AppendOnlyIndexVec::new();
148-
let _id = source_span.push(krate.spans.inner_span);
149-
debug_assert_eq!(_id, CRATE_DEF_ID);
150-
let untracked = Untracked { cstore, source_span, definitions };
146+
let untracked =
147+
Untracked { cstore, source_span: AppendOnlyIndexVec::new(), definitions };
151148

152149
let qcx = passes::create_global_ctxt(
153150
self.compiler,
@@ -172,9 +169,6 @@ impl<'tcx> Queries<'tcx> {
172169
)));
173170
feed.crate_for_resolver(tcx.arena.alloc(Steal::new((krate, pre_configured_attrs))));
174171
feed.output_filenames(Arc::new(outputs));
175-
176-
let feed = tcx.feed_local_def_id(CRATE_DEF_ID);
177-
feed.def_kind(DefKind::Mod);
178172
});
179173
Ok(qcx)
180174
})

compiler/rustc_middle/src/query/mod.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,11 @@ rustc_queries! {
125125
}
126126

127127
query resolutions(_: ()) -> &'tcx ty::ResolverGlobalCtxt {
128-
feedable
129128
no_hash
130129
desc { "getting the resolver outputs" }
131130
}
132131

133-
query resolver_for_lowering(_: ()) -> &'tcx Steal<(ty::ResolverAstLowering, Lrc<ast::Crate>)> {
132+
query resolver_for_lowering_raw(_: ()) -> (&'tcx Steal<(ty::ResolverAstLowering, Lrc<ast::Crate>)>, &'tcx ty::ResolverGlobalCtxt) {
134133
eval_always
135134
no_hash
136135
desc { "getting the resolver for lowering" }
@@ -2221,7 +2220,6 @@ rustc_queries! {
22212220
/// Should not be called for the local crate before the resolver outputs are created, as it
22222221
/// is only fed there.
22232222
query stripped_cfg_items(cnum: CrateNum) -> &'tcx [StrippedCfgItem] {
2224-
feedable
22252223
desc { "getting cfg-ed out item names" }
22262224
separate_provide_extern
22272225
}

compiler/rustc_middle/src/ty/context.rs

+67-4
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use rustc_data_structures::profiling::SelfProfilerRef;
3939
use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
4040
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4141
use rustc_data_structures::steal::Steal;
42-
use rustc_data_structures::sync::{self, FreezeReadGuard, Lock, WorkerLocal};
42+
use rustc_data_structures::sync::{self, FreezeReadGuard, Lock, Lrc, WorkerLocal};
4343
#[cfg(parallel_compiler)]
4444
use rustc_data_structures::sync::{DynSend, DynSync};
4545
use rustc_data_structures::unord::UnordSet;
@@ -60,7 +60,7 @@ use rustc_session::config::CrateType;
6060
use rustc_session::cstore::{CrateStoreDyn, Untracked};
6161
use rustc_session::lint::Lint;
6262
use rustc_session::{Limit, MetadataKind, Session};
63-
use rustc_span::def_id::{DefPathHash, StableCrateId};
63+
use rustc_span::def_id::{DefPathHash, StableCrateId, CRATE_DEF_ID};
6464
use rustc_span::symbol::{kw, sym, Ident, Symbol};
6565
use rustc_span::{Span, DUMMY_SP};
6666
use rustc_target::abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx};
@@ -74,6 +74,7 @@ use std::cmp::Ordering;
7474
use std::fmt;
7575
use std::hash::{Hash, Hasher};
7676
use std::iter;
77+
use std::marker::PhantomData;
7778
use std::mem;
7879
use std::ops::{Bound, Deref};
7980

@@ -498,14 +499,55 @@ pub struct TyCtxtFeed<'tcx, KEY: Copy> {
498499
key: KEY,
499500
}
500501

502+
/// Never return a `Feed` from a query. Only queries that create a `DefId` are
503+
/// allowed to feed queries for that `DefId`.
504+
impl<KEY: Copy, CTX> !HashStable<CTX> for TyCtxtFeed<'_, KEY> {}
505+
506+
/// The same as `TyCtxtFeed`, but does not contain a `TyCtxt`.
507+
/// Use this to pass around when you have a `TyCtxt` elsewhere.
508+
/// Just an optimization to save space and not store hundreds of
509+
/// `TyCtxtFeed` in the resolver.
510+
#[derive(Copy, Clone)]
511+
pub struct Feed<'tcx, KEY: Copy> {
512+
_tcx: PhantomData<TyCtxt<'tcx>>,
513+
// Do not allow direct access, as downstream code must not mutate this field.
514+
key: KEY,
515+
}
516+
517+
/// Never return a `Feed` from a query. Only queries that create a `DefId` are
518+
/// allowed to feed queries for that `DefId`.
519+
impl<KEY: Copy, CTX> !HashStable<CTX> for Feed<'_, KEY> {}
520+
521+
impl<T: fmt::Debug + Copy> fmt::Debug for Feed<'_, T> {
522+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523+
self.key.fmt(f)
524+
}
525+
}
526+
527+
/// Some workarounds to use cases that cannot use `create_def`.
528+
/// Do not add new ways to create `TyCtxtFeed` without consulting
529+
/// with T-compiler and making an analysis about why your addition
530+
/// does not cause incremental compilation issues.
501531
impl<'tcx> TyCtxt<'tcx> {
532+
/// Can only be fed before queries are run, and is thus exempt from any
533+
/// incremental issues. Do not use except for the initial query feeding.
502534
pub fn feed_unit_query(self) -> TyCtxtFeed<'tcx, ()> {
535+
self.dep_graph.assert_ignored();
503536
TyCtxtFeed { tcx: self, key: () }
504537
}
538+
539+
/// Can only be fed before queries are run, and is thus exempt from any
540+
/// incremental issues. Do not use except for the initial query feeding.
505541
pub fn feed_local_crate(self) -> TyCtxtFeed<'tcx, CrateNum> {
542+
self.dep_graph.assert_ignored();
506543
TyCtxtFeed { tcx: self, key: LOCAL_CRATE }
507544
}
508-
pub fn feed_local_def_id(self, key: LocalDefId) -> TyCtxtFeed<'tcx, LocalDefId> {
545+
546+
/// Only used in the resolver to register the `CRATE_DEF_ID` `DefId` and feed
547+
/// some queries for it. It will panic if used twice.
548+
pub fn create_local_crate_def_id(self, span: Span) -> TyCtxtFeed<'tcx, LocalDefId> {
549+
let key = self.untracked().source_span.push(span);
550+
assert_eq!(key, CRATE_DEF_ID);
509551
TyCtxtFeed { tcx: self, key }
510552
}
511553

@@ -523,6 +565,23 @@ impl<'tcx, KEY: Copy> TyCtxtFeed<'tcx, KEY> {
523565
pub fn key(&self) -> KEY {
524566
self.key
525567
}
568+
569+
#[inline(always)]
570+
pub fn downgrade(self) -> Feed<'tcx, KEY> {
571+
Feed { _tcx: PhantomData, key: self.key }
572+
}
573+
}
574+
575+
impl<'tcx, KEY: Copy> Feed<'tcx, KEY> {
576+
#[inline(always)]
577+
pub fn key(&self) -> KEY {
578+
self.key
579+
}
580+
581+
#[inline(always)]
582+
pub fn upgrade(self, tcx: TyCtxt<'tcx>) -> TyCtxtFeed<'tcx, KEY> {
583+
TyCtxtFeed { tcx, key: self.key }
584+
}
526585
}
527586

528587
impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> {
@@ -1067,7 +1126,7 @@ impl<'tcx> TyCtxt<'tcx> {
10671126
// needs to be re-evaluated.
10681127
self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
10691128

1070-
let feed = self.feed_local_def_id(def_id);
1129+
let feed = TyCtxtFeed { tcx: self, key: def_id };
10711130
feed.def_kind(def_kind);
10721131
// Unique types created for closures participate in type privacy checking.
10731132
// They have visibilities inherited from the module they are defined in.
@@ -2304,6 +2363,10 @@ impl<'tcx> TyCtxt<'tcx> {
23042363
self.resolutions(()).module_children.get(&def_id).map_or(&[], |v| &v[..])
23052364
}
23062365

2366+
pub fn resolver_for_lowering(self) -> &'tcx Steal<(ty::ResolverAstLowering, Lrc<ast::Crate>)> {
2367+
self.resolver_for_lowering_raw(()).0
2368+
}
2369+
23072370
/// Given an `impl_id`, return the trait it implements.
23082371
/// Return `None` if this is an inherent impl.
23092372
pub fn impl_trait_ref(

compiler/rustc_middle/src/ty/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pub use generic_args::*;
3232
pub use generics::*;
3333
pub use intrinsic::IntrinsicDef;
3434
use rustc_ast as ast;
35+
use rustc_ast::expand::StrippedCfgItem;
3536
use rustc_ast::node_id::NodeMap;
3637
pub use rustc_ast_ir::{try_visit, Movability, Mutability};
3738
use rustc_attr as attr;
@@ -85,7 +86,8 @@ pub use self::consts::{
8586
Const, ConstData, ConstInt, ConstKind, Expr, ScalarInt, UnevaluatedConst, ValTree,
8687
};
8788
pub use self::context::{
88-
tls, CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed,
89+
tls, CtxtInterners, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
90+
TyCtxtFeed,
8991
};
9092
pub use self::instance::{Instance, InstanceDef, ShortInstance, UnusedGenericParams};
9193
pub use self::list::List;
@@ -189,6 +191,7 @@ pub struct ResolverGlobalCtxt {
189191
pub doc_link_resolutions: FxHashMap<LocalDefId, DocLinkResMap>,
190192
pub doc_link_traits_in_scope: FxHashMap<LocalDefId, Vec<DefId>>,
191193
pub all_macro_rules: FxHashMap<Symbol, Res<ast::NodeId>>,
194+
pub stripped_cfg_items: Steal<Vec<StrippedCfgItem>>,
192195
}
193196

194197
/// Resolutions that should only be used for lowering.

compiler/rustc_passes/src/debugger_visualizer.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ impl<'ast> rustc_ast::visit::Visitor<'ast> for DebuggerVisualizerCollector<'_> {
8787

8888
/// Traverses and collects the debugger visualizers for a specific crate.
8989
fn debugger_visualizers(tcx: TyCtxt<'_>, _: LocalCrate) -> Vec<DebuggerVisualizerFile> {
90-
let resolver_and_krate = tcx.resolver_for_lowering(()).borrow();
90+
let resolver_and_krate = tcx.resolver_for_lowering().borrow();
9191
let krate = &*resolver_and_krate.1;
9292

9393
let mut visitor = DebuggerVisualizerCollector { sess: tcx.sess, visualizers: Vec::new() };

compiler/rustc_passes/src/lang_items.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
243243

244244
/// Traverses and collects all the lang items in all crates.
245245
fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
246-
let resolver = tcx.resolver_for_lowering(()).borrow();
246+
let resolver = tcx.resolver_for_lowering().borrow();
247247
let (resolver, krate) = &*resolver;
248248

249249
// Initialize the collector.

0 commit comments

Comments
 (0)