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_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_data_structures::sync::Lock;
9 use rustc_errors::{Diagnostic, Handler};
10 use rustc_middle::dep_graph::{self, DepKind, DepNodeIndex, SerializedDepNodeIndex};
11 use rustc_middle::ty::tls::{self, ImplicitCtxt};
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_query_system::dep_graph::HasDepContext;
14 use rustc_query_system::ich::StableHashingContext;
15 use rustc_query_system::query::{
16 QueryContext, QueryJobId, QueryMap, QuerySideEffects, QueryStackFrame,
19 use std::num::NonZeroU64;
20 use thin_vec::ThinVec;
22 #[derive(Copy, Clone)]
23 pub struct QueryCtxt<'tcx> {
24 pub tcx: TyCtxt<'tcx>,
25 pub queries: &'tcx Queries<'tcx>,
28 impl<'tcx> std::ops::Deref for QueryCtxt<'tcx> {
29 type Target = TyCtxt<'tcx>;
32 fn deref(&self) -> &Self::Target {
37 impl<'tcx> HasDepContext for QueryCtxt<'tcx> {
38 type DepKind = rustc_middle::dep_graph::DepKind;
39 type DepContext = TyCtxt<'tcx>;
42 fn dep_context(&self) -> &Self::DepContext {
47 impl QueryContext for QueryCtxt<'_> {
48 fn next_job_id(&self) -> QueryJobId {
51 self.queries.jobs.fetch_add(1, rustc_data_structures::sync::Ordering::Relaxed),
57 fn current_query_job(&self) -> Option<QueryJobId> {
58 tls::with_related_context(**self, |icx| icx.query)
61 fn try_collect_active_jobs(&self) -> Option<QueryMap> {
62 self.queries.try_collect_active_jobs(**self)
65 // Interactions with on_disk_cache
66 fn load_side_effects(&self, prev_dep_node_index: SerializedDepNodeIndex) -> QuerySideEffects {
70 .map(|c| c.load_side_effects(**self, prev_dep_node_index))
74 fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
75 if let Some(c) = self.queries.on_disk_cache.as_ref() {
76 c.store_side_effects(dep_node_index, side_effects)
80 fn store_side_effects_for_anon_node(
82 dep_node_index: DepNodeIndex,
83 side_effects: QuerySideEffects,
85 if let Some(c) = self.queries.on_disk_cache.as_ref() {
86 c.store_side_effects_for_anon_node(dep_node_index, side_effects)
90 /// Executes a job by changing the `ImplicitCtxt` to point to the
91 /// new query job while it executes. It returns the diagnostics
92 /// captured during execution and the actual result.
98 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
99 compute: impl FnOnce() -> R,
101 // The `TyCtxt` stored in TLS has the same global interner lifetime
102 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
103 // when accessing the `ImplicitCtxt`.
104 tls::with_related_context(**self, move |current_icx| {
105 if depth_limit && !self.recursion_limit().value_within_limit(current_icx.query_depth) {
106 self.depth_limit_error();
109 // Update the `ImplicitCtxt` to point to our new query job.
110 let new_icx = ImplicitCtxt {
114 query_depth: current_icx.query_depth + depth_limit as usize,
115 task_deps: current_icx.task_deps,
118 // Use the `ImplicitCtxt` while we execute the query.
119 tls::enter_context(&new_icx, |_| {
120 rustc_data_structures::stack::ensure_sufficient_stack(compute)
126 impl<'tcx> QueryCtxt<'tcx> {
128 pub fn from_tcx(tcx: TyCtxt<'tcx>) -> Self {
129 let queries = tcx.queries.as_any();
130 let queries = unsafe {
131 let queries = std::mem::transmute::<&dyn Any, &dyn Any>(queries);
132 let queries = queries.downcast_ref().unwrap();
133 let queries = std::mem::transmute::<&Queries<'_>, &Queries<'_>>(queries);
136 QueryCtxt { tcx, queries }
139 pub(crate) fn on_disk_cache(self) -> Option<&'tcx on_disk_cache::OnDiskCache<'tcx>> {
140 self.queries.on_disk_cache.as_ref()
143 pub(super) fn encode_query_results(
145 encoder: &mut on_disk_cache::CacheEncoder<'_, 'tcx>,
146 query_result_index: &mut on_disk_cache::EncodedDepNodeIndex,
148 macro_rules! encode_queries {
149 ($($query:ident,)*) => {
151 on_disk_cache::encode_query_results::<_, super::queries::$query<'_>>(
160 rustc_cached_queries!(encode_queries!);
163 pub fn try_print_query_stack(
165 query: Option<QueryJobId>,
167 num_frames: Option<usize>,
169 rustc_query_system::query::print_query_stack(self, query, handler, num_frames)
173 macro_rules! handle_cycle_error {
174 ([][$tcx: expr, $error:expr]) => {{
176 Value::from_cycle_error($tcx)
178 ([(fatal_cycle) $($rest:tt)*][$tcx:expr, $error:expr]) => {{
180 $tcx.sess.abort_if_errors();
183 ([(cycle_delay_bug) $($rest:tt)*][$tcx:expr, $error:expr]) => {{
184 $error.delay_as_bug();
185 Value::from_cycle_error($tcx)
187 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
188 handle_cycle_error!([$($modifiers)*][$($args)*])
192 macro_rules! is_anon {
196 ([(anon) $($rest:tt)*]) => {{
199 ([$other:tt $($modifiers:tt)*]) => {
200 is_anon!([$($modifiers)*])
204 macro_rules! is_eval_always {
208 ([(eval_always) $($rest:tt)*]) => {{
211 ([$other:tt $($modifiers:tt)*]) => {
212 is_eval_always!([$($modifiers)*])
216 macro_rules! depth_limit {
220 ([(depth_limit) $($rest:tt)*]) => {{
223 ([$other:tt $($modifiers:tt)*]) => {
224 depth_limit!([$($modifiers)*])
228 macro_rules! hash_result {
230 Some(dep_graph::hash_result)
232 ([(no_hash) $($rest:tt)*]) => {{
235 ([$other:tt $($modifiers:tt)*]) => {
236 hash_result!([$($modifiers)*])
240 macro_rules! get_provider {
241 ([][$tcx:expr, $name:ident, $key:expr]) => {{
242 $tcx.queries.local_providers.$name
244 ([(separate_provide_extern) $($rest:tt)*][$tcx:expr, $name:ident, $key:expr]) => {{
245 if $key.query_crate_is_local() {
246 $tcx.queries.local_providers.$name
248 $tcx.queries.extern_providers.$name
251 ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
252 get_provider!([$($modifiers)*][$($args)*])
256 pub(crate) fn create_query_frame<
258 K: Copy + Key + for<'a> HashStable<StableHashingContext<'a>>,
260 tcx: QueryCtxt<'tcx>,
261 do_describe: fn(QueryCtxt<'tcx>, K) -> String,
265 ) -> QueryStackFrame {
266 // Disable visible paths printing for performance reasons.
267 // Showing visible path instead of any path is not that important in production.
268 let description = ty::print::with_no_visible_paths!(
269 // Force filename-line mode to avoid invoking `type_of` query.
270 ty::print::with_forced_impl_filename_line!(do_describe(tcx, key))
273 if tcx.sess.verbose() { format!("{} [{}]", description, name) } else { description };
274 let span = if kind == dep_graph::DepKind::def_span {
275 // The `def_span` query is used to calculate `default_span`,
276 // so exit to avoid infinite recursion.
279 Some(key.default_span(*tcx))
281 let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
282 // Try to avoid infinite recursion.
286 .and_then(|def_id| def_id.as_local())
287 .and_then(|def_id| tcx.opt_def_kind(def_id))
290 tcx.with_stable_hashing_context(|mut hcx| {
291 let mut hasher = StableHasher::new();
292 std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
293 key.hash_stable(&mut hcx, &mut hasher);
294 hasher.finish::<u64>()
298 QueryStackFrame::new(name, description, span, def_kind, hash)
301 // NOTE: `$V` isn't used here, but we still need to match on it so it can be passed to other macros
302 // invoked by `rustc_query_append`.
303 macro_rules! define_queries {
306 [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
307 define_queries_struct! {
308 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
314 // Create an eponymous constructor for each query.
315 $(#[allow(nonstandard_style)] $(#[$attr])*
316 pub fn $name<'tcx>(tcx: QueryCtxt<'tcx>, key: <queries::$name<'tcx> as QueryConfig>::Key) -> QueryStackFrame {
317 let kind = dep_graph::DepKind::$name;
318 let name = stringify!($name);
319 $crate::plumbing::create_query_frame(tcx, queries::$name::describe, key, kind, name)
323 #[allow(nonstandard_style)]
325 use std::marker::PhantomData;
327 $(pub struct $name<'tcx> {
328 data: PhantomData<&'tcx ()>
332 $(impl<'tcx> QueryConfig for queries::$name<'tcx> {
333 type Key = query_keys::$name<'tcx>;
334 type Value = query_values::$name<'tcx>;
335 type Stored = query_stored::$name<'tcx>;
336 const NAME: &'static str = stringify!($name);
339 impl<'tcx> QueryDescription<QueryCtxt<'tcx>> for queries::$name<'tcx> {
340 rustc_query_description! { $name }
342 type Cache = query_storage::$name<'tcx>;
345 fn query_state<'a>(tcx: QueryCtxt<'tcx>) -> &'a QueryState<Self::Key>
346 where QueryCtxt<'tcx>: 'a
352 fn query_cache<'a>(tcx: QueryCtxt<'tcx>) -> &'a Self::Cache
355 &tcx.query_caches.$name
359 fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
360 QueryVTable<QueryCtxt<'tcx>, Self::Key, Self::Value>
362 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
363 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
365 anon: is_anon!([$($modifiers)*]),
366 eval_always: is_eval_always!([$($modifiers)*]),
367 depth_limit: depth_limit!([$($modifiers)*]),
368 dep_kind: dep_graph::DepKind::$name,
369 hash_result: hash_result!([$($modifiers)*]),
370 handle_cycle_error: |tcx, mut error| handle_cycle_error!([$($modifiers)*][tcx, error]),
373 try_load_from_disk: Self::TRY_LOAD_FROM_DISK,
378 #[allow(nonstandard_style)]
379 mod query_callbacks {
381 use rustc_middle::dep_graph::DepNode;
382 use rustc_query_system::dep_graph::DepNodeParams;
383 use rustc_query_system::query::{force_query, QueryDescription};
384 use rustc_query_system::dep_graph::FingerprintStyle;
386 // We use this for most things when incr. comp. is turned off.
387 pub fn Null() -> DepKindStruct {
390 is_eval_always: false,
391 fingerprint_style: FingerprintStyle::Unit,
392 force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
393 try_load_from_on_disk_cache: None,
397 // We use this for the forever-red node.
398 pub fn Red() -> DepKindStruct {
401 is_eval_always: false,
402 fingerprint_style: FingerprintStyle::Unit,
403 force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
404 try_load_from_on_disk_cache: None,
408 pub fn TraitSelect() -> DepKindStruct {
411 is_eval_always: false,
412 fingerprint_style: FingerprintStyle::Unit,
413 force_from_dep_node: None,
414 try_load_from_on_disk_cache: None,
418 pub fn CompileCodegenUnit() -> DepKindStruct {
421 is_eval_always: false,
422 fingerprint_style: FingerprintStyle::Opaque,
423 force_from_dep_node: None,
424 try_load_from_on_disk_cache: None,
428 pub fn CompileMonoItem() -> DepKindStruct {
431 is_eval_always: false,
432 fingerprint_style: FingerprintStyle::Opaque,
433 force_from_dep_node: None,
434 try_load_from_on_disk_cache: None,
438 $(pub(crate) fn $name()-> DepKindStruct {
439 let is_anon = is_anon!([$($modifiers)*]);
440 let is_eval_always = is_eval_always!([$($modifiers)*]);
442 let fingerprint_style =
443 <<queries::$name<'_> as QueryConfig>::Key as DepNodeParams<TyCtxt<'_>>>::fingerprint_style();
445 if is_anon || !fingerprint_style.reconstructible() {
446 return DepKindStruct {
450 force_from_dep_node: None,
451 try_load_from_on_disk_cache: None,
456 fn recover<'tcx>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> Option<<queries::$name<'tcx> as QueryConfig>::Key> {
457 <<queries::$name<'_> as QueryConfig>::Key as DepNodeParams<TyCtxt<'_>>>::recover(tcx, &dep_node)
460 fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: DepNode) -> bool {
461 if let Some(key) = recover(tcx, dep_node) {
462 #[cfg(debug_assertions)]
463 let _guard = tracing::span!(tracing::Level::TRACE, stringify!($name), ?key).entered();
464 let tcx = QueryCtxt::from_tcx(tcx);
465 force_query::<queries::$name<'_>, _>(tcx, key, dep_node);
472 fn try_load_from_on_disk_cache(tcx: TyCtxt<'_>, dep_node: DepNode) {
473 debug_assert!(tcx.dep_graph.is_green(&dep_node));
475 let key = recover(tcx, dep_node).unwrap_or_else(|| panic!("Failed to recover key for {:?} with hash {}", dep_node, dep_node.hash));
476 if queries::$name::cache_on_disk(tcx, &key) {
477 let _ = tcx.$name(key);
485 force_from_dep_node: Some(force_from_dep_node),
486 try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache),
491 pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct] {
492 arena.alloc_from_iter(make_dep_kind_array!(query_callbacks))
497 macro_rules! define_queries_struct {
499 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
500 pub struct Queries<'tcx> {
501 local_providers: Box<Providers>,
502 extern_providers: Box<ExternProviders>,
504 pub on_disk_cache: Option<OnDiskCache<'tcx>>,
508 $($(#[$attr])* $name: QueryState<<queries::$name<'tcx> as QueryConfig>::Key>,)*
511 impl<'tcx> Queries<'tcx> {
513 local_providers: Providers,
514 extern_providers: ExternProviders,
515 on_disk_cache: Option<OnDiskCache<'tcx>>,
518 local_providers: Box::new(local_providers),
519 extern_providers: Box::new(extern_providers),
521 jobs: AtomicU64::new(1),
522 $($name: Default::default()),*
526 pub(crate) fn try_collect_active_jobs(
529 ) -> Option<QueryMap> {
530 let tcx = QueryCtxt { tcx, queries: self };
531 let mut jobs = QueryMap::default();
534 self.$name.try_collect_active_jobs(
545 impl<'tcx> QueryEngine<'tcx> for Queries<'tcx> {
546 fn as_any(&'tcx self) -> &'tcx dyn std::any::Any {
547 let this = unsafe { std::mem::transmute::<&Queries<'_>, &Queries<'_>>(self) };
551 fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool {
552 let qcx = QueryCtxt { tcx, queries: self };
553 tcx.dep_graph.try_mark_green(qcx, dep_node).is_some()
558 #[tracing::instrument(level = "trace", skip(self, tcx))]
563 key: <queries::$name<'tcx> as QueryConfig>::Key,
565 ) -> Option<query_stored::$name<'tcx>> {
566 let qcx = QueryCtxt { tcx, queries: self };
567 get_query::<queries::$name<'tcx>, _>(qcx, span, key, mode)