1 //! The implementation of the query system itself. This defines the macros that
2 //! generate the actual methods on tcx which find and execute the provider,
3 //! manage the caches, and so forth.
6 use crate::{on_disk_cache, Queries};
7 use rustc_middle::dep_graph::{self, DepKind, DepNodeIndex, SerializedDepNodeIndex};
8 use rustc_middle::ty::tls::{self, ImplicitCtxt};
9 use rustc_middle::ty::{self, TyCtxt};
10 use rustc_query_system::dep_graph::HasDepContext;
11 use rustc_query_system::ich::StableHashingContext;
12 use rustc_query_system::query::{
13 QueryContext, QueryJobId, QueryMap, QuerySideEffects, QueryStackFrame,
16 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
17 use rustc_data_structures::sync::Lock;
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_errors::{Diagnostic, Handler};
22 use std::num::NonZeroU64;
24 #[derive(Copy, Clone)]
25 pub struct QueryCtxt<'tcx> {
26 pub tcx: TyCtxt<'tcx>,
27 pub queries: &'tcx Queries<'tcx>,
30 impl<'tcx> std::ops::Deref for QueryCtxt<'tcx> {
31 type Target = TyCtxt<'tcx>;
34 fn deref(&self) -> &Self::Target {
39 impl<'tcx> HasDepContext for QueryCtxt<'tcx> {
40 type DepKind = rustc_middle::dep_graph::DepKind;
41 type DepContext = TyCtxt<'tcx>;
44 fn dep_context(&self) -> &Self::DepContext {
49 impl QueryContext for QueryCtxt<'_> {
50 fn next_job_id(&self) -> QueryJobId {
53 self.queries.jobs.fetch_add(1, rustc_data_structures::sync::Ordering::Relaxed),
59 fn current_query_job(&self) -> Option<QueryJobId> {
60 tls::with_related_context(**self, |icx| icx.query)
63 fn try_collect_active_jobs(&self) -> Option<QueryMap> {
64 self.queries.try_collect_active_jobs(**self)
67 // Interactions with on_disk_cache
68 fn load_side_effects(&self, prev_dep_node_index: SerializedDepNodeIndex) -> QuerySideEffects {
72 .map(|c| c.load_side_effects(**self, prev_dep_node_index))
76 fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
77 if let Some(c) = self.queries.on_disk_cache.as_ref() {
78 c.store_side_effects(dep_node_index, side_effects)
82 fn store_side_effects_for_anon_node(
84 dep_node_index: DepNodeIndex,
85 side_effects: QuerySideEffects,
87 if let Some(c) = self.queries.on_disk_cache.as_ref() {
88 c.store_side_effects_for_anon_node(dep_node_index, side_effects)
92 /// Executes a job by changing the `ImplicitCtxt` to point to the
93 /// new query job while it executes. It returns the diagnostics
94 /// captured during execution and the actual result.
100 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
101 compute: impl FnOnce() -> R,
103 // The `TyCtxt` stored in TLS has the same global interner lifetime
104 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
105 // when accessing the `ImplicitCtxt`.
106 tls::with_related_context(**self, move |current_icx| {
107 if depth_limit && !self.recursion_limit().value_within_limit(current_icx.query_depth) {
108 self.depth_limit_error();
111 // Update the `ImplicitCtxt` to point to our new query job.
112 let new_icx = ImplicitCtxt {
116 query_depth: current_icx.query_depth + depth_limit as usize,
117 task_deps: current_icx.task_deps,
120 // Use the `ImplicitCtxt` while we execute the query.
121 tls::enter_context(&new_icx, |_| {
122 rustc_data_structures::stack::ensure_sufficient_stack(compute)
128 impl<'tcx> QueryCtxt<'tcx> {
130 pub fn from_tcx(tcx: TyCtxt<'tcx>) -> Self {
131 let queries = tcx.queries.as_any();
132 let queries = unsafe {
133 let queries = std::mem::transmute::<&dyn Any, &dyn Any>(queries);
134 let queries = queries.downcast_ref().unwrap();
135 let queries = std::mem::transmute::<&Queries<'_>, &Queries<'_>>(queries);
138 QueryCtxt { tcx, queries }
141 pub(crate) fn on_disk_cache(self) -> Option<&'tcx on_disk_cache::OnDiskCache<'tcx>> {
142 self.queries.on_disk_cache.as_ref()
145 pub(super) fn encode_query_results(
147 encoder: &mut on_disk_cache::CacheEncoder<'_, 'tcx>,
148 query_result_index: &mut on_disk_cache::EncodedDepNodeIndex,
150 macro_rules! encode_queries {
151 ($($query:ident,)*) => {
153 on_disk_cache::encode_query_results::<_, super::queries::$query<'_>>(
162 rustc_cached_queries!(encode_queries!);
165 pub fn try_print_query_stack(
167 query: Option<QueryJobId>,
169 num_frames: Option<usize>,
171 rustc_query_system::query::print_query_stack(self, query, handler, num_frames)
175 macro_rules! handle_cycle_error {
176 ([][$tcx: expr, $error:expr]) => {{
178 Value::from_cycle_error($tcx)
180 ([(fatal_cycle) $($rest:tt)*][$tcx:expr, $error:expr]) => {{
182 $tcx.sess.abort_if_errors();
185 ([(cycle_delay_bug) $($rest:tt)*][$tcx:expr, $error:expr]) => {{
186 $error.delay_as_bug();
187 Value::from_cycle_error($tcx)
189 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
190 handle_cycle_error!([$($modifiers)*][$($args)*])
194 macro_rules! is_anon {
198 ([(anon) $($rest:tt)*]) => {{
201 ([$other:tt $($modifiers:tt)*]) => {
202 is_anon!([$($modifiers)*])
206 macro_rules! is_eval_always {
210 ([(eval_always) $($rest:tt)*]) => {{
213 ([$other:tt $($modifiers:tt)*]) => {
214 is_eval_always!([$($modifiers)*])
218 macro_rules! depth_limit {
222 ([(depth_limit) $($rest:tt)*]) => {{
225 ([$other:tt $($modifiers:tt)*]) => {
226 depth_limit!([$($modifiers)*])
230 macro_rules! hash_result {
232 Some(dep_graph::hash_result)
234 ([(no_hash) $($rest:tt)*]) => {{
237 ([$other:tt $($modifiers:tt)*]) => {
238 hash_result!([$($modifiers)*])
242 macro_rules! get_provider {
243 ([][$tcx:expr, $name:ident, $key:expr]) => {{
244 $tcx.queries.local_providers.$name
246 ([(separate_provide_extern) $($rest:tt)*][$tcx:expr, $name:ident, $key:expr]) => {{
247 if $key.query_crate_is_local() {
248 $tcx.queries.local_providers.$name
250 $tcx.queries.extern_providers.$name
253 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
254 get_provider!([$($modifiers)*][$($args)*])
258 pub(crate) fn create_query_frame<
260 K: Copy + Key + for<'a> HashStable<StableHashingContext<'a>>,
262 tcx: QueryCtxt<'tcx>,
263 do_describe: fn(QueryCtxt<'tcx>, K) -> String,
267 ) -> QueryStackFrame {
268 // Disable visible paths printing for performance reasons.
269 // Showing visible path instead of any path is not that important in production.
270 let description = ty::print::with_no_visible_paths!(
271 // Force filename-line mode to avoid invoking `type_of` query.
272 ty::print::with_forced_impl_filename_line!(do_describe(tcx, key))
275 if tcx.sess.verbose() { format!("{} [{}]", description, name) } else { description };
276 let span = if kind == dep_graph::DepKind::def_span {
277 // The `def_span` query is used to calculate `default_span`,
278 // so exit to avoid infinite recursion.
281 Some(key.default_span(*tcx))
283 let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
284 // Try to avoid infinite recursion.
288 .and_then(|def_id| def_id.as_local())
289 .and_then(|def_id| tcx.opt_def_kind(def_id))
292 tcx.with_stable_hashing_context(|mut hcx| {
293 let mut hasher = StableHasher::new();
294 std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
295 key.hash_stable(&mut hcx, &mut hasher);
296 hasher.finish::<u64>()
300 QueryStackFrame::new(name, description, span, def_kind, hash)
303 // NOTE: `$V` isn't used here, but we still need to match on it so it can be passed to other macros
304 // invoked by `rustc_query_append`.
305 macro_rules! define_queries {
308 [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
309 define_queries_struct! {
310 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
316 // Create an eponymous constructor for each query.
317 $(#[allow(nonstandard_style)] $(#[$attr])*
318 pub fn $name<'tcx>(tcx: QueryCtxt<'tcx>, key: <queries::$name<'tcx> as QueryConfig>::Key) -> QueryStackFrame {
319 let kind = dep_graph::DepKind::$name;
320 let name = stringify!($name);
321 $crate::plumbing::create_query_frame(tcx, queries::$name::describe, key, kind, name)
325 #[allow(nonstandard_style)]
327 use std::marker::PhantomData;
329 $(pub struct $name<'tcx> {
330 data: PhantomData<&'tcx ()>
334 $(impl<'tcx> QueryConfig for queries::$name<'tcx> {
335 type Key = query_keys::$name<'tcx>;
336 type Value = query_values::$name<'tcx>;
337 type Stored = query_stored::$name<'tcx>;
338 const NAME: &'static str = stringify!($name);
341 impl<'tcx> QueryDescription<QueryCtxt<'tcx>> for queries::$name<'tcx> {
342 rustc_query_description! { $name<'tcx> }
344 type Cache = query_storage::$name<'tcx>;
347 fn query_state<'a>(tcx: QueryCtxt<'tcx>) -> &'a QueryState<Self::Key>
348 where QueryCtxt<'tcx>: 'a
354 fn query_cache<'a>(tcx: QueryCtxt<'tcx>) -> &'a Self::Cache
357 &tcx.query_caches.$name
361 fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
362 QueryVTable<QueryCtxt<'tcx>, Self::Key, Self::Value>
364 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
365 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
367 anon: is_anon!([$($modifiers)*]),
368 eval_always: is_eval_always!([$($modifiers)*]),
369 depth_limit: depth_limit!([$($modifiers)*]),
370 dep_kind: dep_graph::DepKind::$name,
371 hash_result: hash_result!([$($modifiers)*]),
372 handle_cycle_error: |tcx, mut error| handle_cycle_error!([$($modifiers)*][tcx, error]),
375 try_load_from_disk: Self::TRY_LOAD_FROM_DISK,
380 #[allow(nonstandard_style)]
381 mod query_callbacks {
383 use rustc_middle::dep_graph::DepNode;
384 use rustc_query_system::dep_graph::DepNodeParams;
385 use rustc_query_system::query::{force_query, QueryDescription};
386 use rustc_query_system::dep_graph::FingerprintStyle;
388 // We use this for most things when incr. comp. is turned off.
389 pub fn Null() -> DepKindStruct {
392 is_eval_always: false,
393 fingerprint_style: FingerprintStyle::Unit,
394 force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
395 try_load_from_on_disk_cache: None,
399 // We use this for the forever-red node.
400 pub fn Red() -> DepKindStruct {
403 is_eval_always: false,
404 fingerprint_style: FingerprintStyle::Unit,
405 force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
406 try_load_from_on_disk_cache: None,
410 pub fn TraitSelect() -> DepKindStruct {
413 is_eval_always: false,
414 fingerprint_style: FingerprintStyle::Unit,
415 force_from_dep_node: None,
416 try_load_from_on_disk_cache: None,
420 pub fn CompileCodegenUnit() -> DepKindStruct {
423 is_eval_always: false,
424 fingerprint_style: FingerprintStyle::Opaque,
425 force_from_dep_node: None,
426 try_load_from_on_disk_cache: None,
430 pub fn CompileMonoItem() -> DepKindStruct {
433 is_eval_always: false,
434 fingerprint_style: FingerprintStyle::Opaque,
435 force_from_dep_node: None,
436 try_load_from_on_disk_cache: None,
440 $(pub(crate) fn $name()-> DepKindStruct {
441 let is_anon = is_anon!([$($modifiers)*]);
442 let is_eval_always = is_eval_always!([$($modifiers)*]);
444 let fingerprint_style =
445 <<queries::$name<'_> as QueryConfig>::Key as DepNodeParams<TyCtxt<'_>>>::fingerprint_style();
447 if is_anon || !fingerprint_style.reconstructible() {
448 return DepKindStruct {
452 force_from_dep_node: None,
453 try_load_from_on_disk_cache: None,
458 fn recover<'tcx>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> Option<<queries::$name<'tcx> as QueryConfig>::Key> {
459 <<queries::$name<'_> as QueryConfig>::Key as DepNodeParams<TyCtxt<'_>>>::recover(tcx, &dep_node)
462 fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: DepNode) -> bool {
463 if let Some(key) = recover(tcx, dep_node) {
464 #[cfg(debug_assertions)]
465 let _guard = tracing::span!(tracing::Level::TRACE, stringify!($name), ?key).entered();
466 let tcx = QueryCtxt::from_tcx(tcx);
467 force_query::<queries::$name<'_>, _>(tcx, key, dep_node);
474 fn try_load_from_on_disk_cache(tcx: TyCtxt<'_>, dep_node: DepNode) {
475 debug_assert!(tcx.dep_graph.is_green(&dep_node));
477 let key = recover(tcx, dep_node).unwrap_or_else(|| panic!("Failed to recover key for {:?} with hash {}", dep_node, dep_node.hash));
478 if queries::$name::cache_on_disk(tcx, &key) {
479 let _ = tcx.$name(key);
487 force_from_dep_node: Some(force_from_dep_node),
488 try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache),
493 pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct] {
494 arena.alloc_from_iter(make_dep_kind_array!(query_callbacks))
499 macro_rules! define_queries_struct {
501 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
502 pub struct Queries<'tcx> {
503 local_providers: Box<Providers>,
504 extern_providers: Box<ExternProviders>,
506 pub on_disk_cache: Option<OnDiskCache<'tcx>>,
510 $($(#[$attr])* $name: QueryState<<queries::$name<'tcx> as QueryConfig>::Key>,)*
513 impl<'tcx> Queries<'tcx> {
515 local_providers: Providers,
516 extern_providers: ExternProviders,
517 on_disk_cache: Option<OnDiskCache<'tcx>>,
520 local_providers: Box::new(local_providers),
521 extern_providers: Box::new(extern_providers),
523 jobs: AtomicU64::new(1),
524 $($name: Default::default()),*
528 pub(crate) fn try_collect_active_jobs(
531 ) -> Option<QueryMap> {
532 let tcx = QueryCtxt { tcx, queries: self };
533 let mut jobs = QueryMap::default();
536 self.$name.try_collect_active_jobs(
547 impl<'tcx> QueryEngine<'tcx> for Queries<'tcx> {
548 fn as_any(&'tcx self) -> &'tcx dyn std::any::Any {
549 let this = unsafe { std::mem::transmute::<&Queries<'_>, &Queries<'_>>(self) };
553 fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool {
554 let qcx = QueryCtxt { tcx, queries: self };
555 tcx.dep_graph.try_mark_green(qcx, dep_node).is_some()
560 #[tracing::instrument(level = "trace", skip(self, tcx))]
565 key: <queries::$name<'tcx> as QueryConfig>::Key,
567 ) -> Option<query_stored::$name<'tcx>> {
568 let qcx = QueryCtxt { tcx, queries: self };
569 get_query::<queries::$name<'tcx>, _>(qcx, span, key, mode)