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.
5 use crate::dep_graph::{DepKind, DepNode, DepNodeIndex, SerializedDepNodeIndex};
6 use crate::ty::query::config::{QueryConfig, QueryDescription};
7 use crate::ty::query::job::{QueryInfo, QueryJob, QueryJobId, QueryShardJobId};
8 use crate::ty::query::Query;
10 use crate::ty::{self, TyCtxt};
12 #[cfg(not(parallel_compiler))]
13 use rustc_data_structures::cold_path;
14 use rustc_data_structures::fx::{FxHashMap, FxHasher};
15 #[cfg(parallel_compiler)]
16 use rustc_data_structures::profiling::TimingGuard;
17 use rustc_data_structures::sharded::Sharded;
18 use rustc_data_structures::sync::Lock;
19 use rustc_data_structures::thin_vec::ThinVec;
20 use rustc_errors::{struct_span_err, Diagnostic, DiagnosticBuilder, FatalError, Handler, Level};
21 use rustc_span::source_map::DUMMY_SP;
23 use std::collections::hash_map::Entry;
24 use std::hash::{Hash, Hasher};
26 use std::num::NonZeroU32;
29 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
30 pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
31 pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
33 /// Used to generate unique ids for active jobs.
36 #[cfg(debug_assertions)]
37 pub(super) cache_hits: usize,
40 pub(super) struct QueryValue<T> {
42 pub(super) index: DepNodeIndex,
45 impl<T> QueryValue<T> {
46 pub(super) fn new(value: T, dep_node_index: DepNodeIndex) -> QueryValue<T> {
47 QueryValue { value, index: dep_node_index }
51 /// Indicates the state of a query for a given key in a query map.
52 pub(super) enum QueryResult<'tcx> {
53 /// An already executing query. The query job can be used to await for its completion.
54 Started(QueryJob<'tcx>),
56 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
61 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
62 fn default() -> QueryCache<'tcx, M> {
64 results: FxHashMap::default(),
65 active: FxHashMap::default(),
67 #[cfg(debug_assertions)]
73 /// A type representing the responsibility to execute the job in the `job` field.
74 /// This will poison the relevant query if dropped.
75 pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx>> {
76 cache: &'a Sharded<QueryCache<'tcx, Q>>,
81 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
82 /// Either gets a `JobOwner` corresponding the query, allowing us to
83 /// start executing the query, or returns with the result of the query.
84 /// If the query is executing elsewhere, this will wait for it.
85 /// If the query panicked, this will silently panic.
87 /// This function is inlined because that results in a noticeable speed-up
88 /// for some compile-time benchmarks.
90 pub(super) fn try_get(tcx: TyCtxt<'tcx>, span: Span, key: &Q::Key) -> TryGetJob<'a, 'tcx, Q> {
91 // Handling the `query_blocked_prof_timer` is a bit weird because of the
92 // control flow in this function: Blocking is implemented by
93 // awaiting a running job and, once that is done, entering the loop below
94 // again from the top. In that second iteration we will hit the
95 // cache which provides us with the information we need for
96 // finishing the "query-blocked" event.
98 // We thus allocate `query_blocked_prof_timer` outside the loop,
99 // initialize it during the first iteration and finish it during the
101 #[cfg(parallel_compiler)]
102 let mut query_blocked_prof_timer: Option<TimingGuard<'_>> = None;
104 let cache = Q::query_cache(tcx);
106 // We compute the key's hash once and then use it for both the
107 // shard lookup and the hashmap lookup. This relies on the fact
108 // that both of them use `FxHasher`.
109 let mut state = FxHasher::default();
110 key.hash(&mut state);
111 let key_hash = state.finish();
113 let shard = cache.get_shard_index_by_hash(key_hash);
114 let mut lock_guard = cache.get_shard_by_index(shard).lock();
115 let lock = &mut *lock_guard;
117 if let Some((_, value)) =
118 lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
120 if unlikely!(tcx.prof.enabled()) {
121 tcx.prof.query_cache_hit(value.index.into());
123 #[cfg(parallel_compiler)]
125 if let Some(prof_timer) = query_blocked_prof_timer.take() {
126 prof_timer.finish_with_query_invocation_id(value.index.into());
131 let result = (value.value.clone(), value.index);
132 #[cfg(debug_assertions)]
134 lock.cache_hits += 1;
136 return TryGetJob::JobCompleted(result);
139 let latch = match lock.active.entry((*key).clone()) {
140 Entry::Occupied(mut entry) => {
141 match entry.get_mut() {
142 QueryResult::Started(job) => {
143 // For parallel queries, we'll block and wait until the query running
144 // in another thread has completed. Record how long we wait in the
146 #[cfg(parallel_compiler)]
148 query_blocked_prof_timer = Some(tcx.prof.query_blocked());
151 // Create the id of the job we're waiting for
152 let id = QueryJobId::new(job.id, shard, Q::dep_kind());
156 QueryResult::Poisoned => FatalError.raise(),
159 Entry::Vacant(entry) => {
160 // No job entry for this query. Return a new one to be started later.
162 // Generate an id unique within this shard.
163 let id = lock.jobs.checked_add(1).unwrap();
165 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
167 let global_id = QueryJobId::new(id, shard, Q::dep_kind());
170 tls::with_related_context(tcx, |icx| QueryJob::new(id, span, icx.query));
172 entry.insert(QueryResult::Started(job));
174 let owner = JobOwner { cache, id: global_id, key: (*key).clone() };
175 return TryGetJob::NotYetStarted(owner);
178 mem::drop(lock_guard);
180 // If we are single-threaded we know that we have cycle error,
181 // so we just return the error.
182 #[cfg(not(parallel_compiler))]
183 return TryGetJob::Cycle(cold_path(|| {
184 Q::handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span))
187 // With parallel queries we might just have to wait on some other
189 #[cfg(parallel_compiler)]
191 let result = latch.wait_on(tcx, span);
193 if let Err(cycle) = result {
194 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
200 /// Completes the query by updating the query cache with the `result`,
201 /// signals the waiter and forgets the JobOwner, so it won't poison the query
203 pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
204 // We can move out of `self` here because we `mem::forget` it below
205 let key = unsafe { ptr::read(&self.key) };
206 let cache = self.cache;
208 // Forget ourself so our destructor won't poison the query
211 let value = QueryValue::new(result.clone(), dep_node_index);
213 let mut lock = cache.get_shard_by_value(&key).lock();
214 let job = match lock.active.remove(&key).unwrap() {
215 QueryResult::Started(job) => job,
216 QueryResult::Poisoned => panic!(),
218 lock.results.insert(key, value);
222 job.signal_complete();
227 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
229 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
231 let diagnostics = Lock::new(ThinVec::new());
232 let result = f(Some(&diagnostics));
233 (result, diagnostics.into_inner())
236 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
240 // Poison the query so jobs waiting on it panic.
241 let shard = self.cache.get_shard_by_value(&self.key);
243 let mut shard = shard.lock();
244 let job = match shard.active.remove(&self.key).unwrap() {
245 QueryResult::Started(job) => job,
246 QueryResult::Poisoned => panic!(),
248 shard.active.insert(self.key.clone(), QueryResult::Poisoned);
251 // Also signal the completion of the job, so waiters
252 // will continue execution.
253 job.signal_complete();
258 pub struct CycleError<'tcx> {
259 /// The query and related span that uses the cycle.
260 pub(super) usage: Option<(Span, Query<'tcx>)>,
261 pub(super) cycle: Vec<QueryInfo<'tcx>>,
264 /// The result of `try_get_lock`.
265 pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx>> {
266 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
267 NotYetStarted(JobOwner<'a, 'tcx, D>),
269 /// The query was already completed.
270 /// Returns the result of the query and its dep-node index
271 /// if it succeeded or a cycle error if it failed.
272 JobCompleted((D::Value, DepNodeIndex)),
274 /// Trying to execute the query resulted in a cycle.
278 impl<'tcx> TyCtxt<'tcx> {
279 /// Executes a job by changing the `ImplicitCtxt` to point to the
280 /// new query job while it executes. It returns the diagnostics
281 /// captured during execution and the actual result.
283 pub(super) fn start_query<F, R>(
286 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
290 F: FnOnce(TyCtxt<'tcx>) -> R,
292 // The `TyCtxt` stored in TLS has the same global interner lifetime
293 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
294 // when accessing the `ImplicitCtxt`.
295 tls::with_related_context(self, move |current_icx| {
296 // Update the `ImplicitCtxt` to point to our new query job.
297 let new_icx = tls::ImplicitCtxt {
301 layout_depth: current_icx.layout_depth,
302 task_deps: current_icx.task_deps,
305 // Use the `ImplicitCtxt` while we execute the query.
306 tls::enter_context(&new_icx, |_| compute(self))
312 pub(super) fn report_cycle(
314 CycleError { usage, cycle: stack }: CycleError<'tcx>,
315 ) -> DiagnosticBuilder<'tcx> {
316 assert!(!stack.is_empty());
318 let fix_span = |span: Span, query: &Query<'tcx>| {
319 self.sess.source_map().def_span(query.default_span(self, span))
322 // Disable naming impls with types in this path, since that
323 // sometimes cycles itself, leading to extra cycle errors.
324 // (And cycle errors around impls tend to occur during the
325 // collect/coherence phases anyhow.)
326 ty::print::with_forced_impl_filename_line(|| {
327 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
328 let mut err = struct_span_err!(
332 "cycle detected when {}",
333 stack[0].query.describe(self)
336 for i in 1..stack.len() {
337 let query = &stack[i].query;
338 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
339 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
343 "...which again requires {}, completing the cycle",
344 stack[0].query.describe(self)
347 if let Some((span, query)) = usage {
349 fix_span(span, &query),
350 &format!("cycle used when {}", query.describe(self)),
358 pub fn try_print_query_stack(handler: &Handler) {
359 eprintln!("query stack during panic:");
361 // Be careful reyling on global state here: this code is called from
362 // a panic hook, which means that the global `Handler` may be in a weird
363 // state if it was responsible for triggering the panic.
364 tls::with_context_opt(|icx| {
365 if let Some(icx) = icx {
366 let query_map = icx.tcx.queries.try_collect_active_jobs();
368 let mut current_query = icx.query;
371 while let Some(query) = current_query {
373 if let Some(info) = query_map.as_ref().and_then(|map| map.get(&query)) {
378 let mut diag = Diagnostic::new(
383 query_info.info.query.name(),
384 query_info.info.query.describe(icx.tcx)
387 diag.span = icx.tcx.sess.source_map().def_span(query_info.info.span).into();
388 handler.force_print_diagnostic(diag);
390 current_query = query_info.job.parent;
396 eprintln!("end of query stack");
400 pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
401 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
403 let job = match JobOwner::try_get(self, span, &key) {
404 TryGetJob::NotYetStarted(job) => job,
405 TryGetJob::Cycle(result) => return result,
406 TryGetJob::JobCompleted((v, index)) => {
407 self.dep_graph.read_index(index);
412 // Fast path for when incr. comp. is off. `to_dep_node` is
413 // expensive for some `DepKind`s.
414 if !self.dep_graph.is_fully_enabled() {
415 let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
416 return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
420 let prof_timer = self.prof.query_provider();
422 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
423 self.start_query(job.id, diagnostics, |tcx| {
424 tcx.dep_graph.with_anon_task(Q::dep_kind(), || Q::compute(tcx, key))
428 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
430 self.dep_graph.read_index(dep_node_index);
432 if unlikely!(!diagnostics.is_empty()) {
435 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
438 job.complete(&result, dep_node_index);
443 let dep_node = Q::to_dep_node(self, &key);
446 // The diagnostics for this query will be
447 // promoted to the current session during
448 // `try_mark_green()`, so we can ignore them here.
449 let loaded = self.start_query(job.id, None, |tcx| {
450 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
451 marked.map(|(prev_dep_node_index, dep_node_index)| {
453 tcx.load_from_disk_and_cache_in_memory::<Q>(
463 if let Some((result, dep_node_index)) = loaded {
464 job.complete(&result, dep_node_index);
469 let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
470 self.dep_graph.read_index(dep_node_index);
474 fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'tcx>>(
477 prev_dep_node_index: SerializedDepNodeIndex,
478 dep_node_index: DepNodeIndex,
481 // Note this function can be called concurrently from the same query
482 // We must ensure that this is handled correctly.
484 debug_assert!(self.dep_graph.is_green(dep_node));
486 // First we try to load the result from the on-disk cache.
487 let result = if Q::cache_on_disk(self, key.clone(), None)
488 && self.sess.opts.debugging_opts.incremental_queries
490 let prof_timer = self.prof.incr_cache_loading();
491 let result = Q::try_load_from_disk(self, prev_dep_node_index);
492 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
494 // We always expect to find a cached result for things that
495 // can be forced from `DepNode`.
497 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
498 "missing on-disk cache entry for {:?}",
503 // Some things are never cached on disk.
507 let result = if let Some(result) = result {
510 // We could not load a result from the on-disk cache, so
512 let prof_timer = self.prof.query_provider();
514 // The dep-graph for this computation is already in-place.
515 let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
517 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
522 // If `-Zincremental-verify-ich` is specified, re-hash results from
523 // the cache and make sure that they have the expected fingerprint.
524 if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
525 self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
533 fn incremental_verify_ich<Q: QueryDescription<'tcx>>(
537 dep_node_index: DepNodeIndex,
539 use crate::ich::Fingerprint;
542 Some(self.dep_graph.fingerprint_of(dep_node_index))
543 == self.dep_graph.prev_fingerprint_of(dep_node),
544 "fingerprint for green query instance not loaded from cache: {:?}",
548 debug!("BEGIN verify_ich({:?})", dep_node);
549 let mut hcx = self.create_stable_hashing_context();
551 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
552 debug!("END verify_ich({:?})", dep_node);
554 let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
556 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
560 fn force_query_with_job<Q: QueryDescription<'tcx>>(
563 job: JobOwner<'_, 'tcx, Q>,
565 ) -> (Q::Value, DepNodeIndex) {
566 // If the following assertion triggers, it can have two reasons:
567 // 1. Something is wrong with DepNode creation, either here or
568 // in `DepGraph::try_mark_green()`.
569 // 2. Two distinct query keys get mapped to the same `DepNode`
570 // (see for example #48923).
572 !self.dep_graph.dep_node_exists(&dep_node),
573 "forcing query with already existing `DepNode`\n\
580 let prof_timer = self.prof.query_provider();
582 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
583 self.start_query(job.id, diagnostics, |tcx| {
585 tcx.dep_graph.with_eval_always_task(
593 tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
598 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
600 if unlikely!(!diagnostics.is_empty()) {
601 if dep_node.kind != crate::dep_graph::DepKind::Null {
602 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
606 job.complete(&result, dep_node_index);
608 (result, dep_node_index)
611 /// Ensure that either this query has all green inputs or been executed.
612 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
614 /// This function is particularly useful when executing passes for their
615 /// side-effects -- e.g., in order to report errors for erroneous programs.
617 /// Note: The optimization is only available during incr. comp.
618 pub(super) fn ensure_query<Q: QueryDescription<'tcx>>(self, key: Q::Key) -> () {
620 let _ = self.get_query::<Q>(DUMMY_SP, key);
624 // Ensuring an anonymous query makes no sense
627 let dep_node = Q::to_dep_node(self, &key);
629 match self.dep_graph.try_mark_green_and_read(self, &dep_node) {
631 // A None return from `try_mark_green_and_read` means that this is either
632 // a new dep node or that the dep node has already been marked red.
633 // Either way, we can't call `dep_graph.read()` as we don't have the
634 // DepNodeIndex. We must invoke the query itself. The performance cost
635 // this introduces should be negligible as we'll immediately hit the
636 // in-memory cache, or another query down the line will.
637 let _ = self.get_query::<Q>(DUMMY_SP, key);
639 Some((_, dep_node_index)) => {
640 self.prof.query_cache_hit(dep_node_index.into());
646 fn force_query<Q: QueryDescription<'tcx>>(self, key: Q::Key, span: Span, dep_node: DepNode) {
647 // We may be concurrently trying both execute and force a query.
648 // Ensure that only one of them runs the query.
649 let job = match JobOwner::try_get(self, span, &key) {
650 TryGetJob::NotYetStarted(job) => job,
651 TryGetJob::Cycle(_) | TryGetJob::JobCompleted(_) => return,
653 self.force_query_with_job::<Q>(key, job, dep_node);
657 macro_rules! handle_cycle_error {
658 ([][$tcx: expr, $error:expr]) => {{
659 $tcx.report_cycle($error).emit();
660 Value::from_cycle_error($tcx)
662 ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
663 $tcx.report_cycle($error).emit();
664 $tcx.sess.abort_if_errors();
667 ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
668 $tcx.report_cycle($error).delay_as_bug();
669 Value::from_cycle_error($tcx)
671 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
672 handle_cycle_error!([$($modifiers),*][$($args)*])
676 macro_rules! is_anon {
680 ([anon$(, $modifiers:ident)*]) => {{
683 ([$other:ident$(, $modifiers:ident)*]) => {
684 is_anon!([$($modifiers),*])
688 macro_rules! is_eval_always {
692 ([eval_always$(, $modifiers:ident)*]) => {{
695 ([$other:ident$(, $modifiers:ident)*]) => {
696 is_eval_always!([$($modifiers),*])
700 macro_rules! hash_result {
701 ([][$hcx:expr, $result:expr]) => {{
702 dep_graph::hash_result($hcx, &$result)
704 ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
707 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
708 hash_result!([$($modifiers),*][$($args)*])
712 macro_rules! define_queries {
713 (<$tcx:tt> $($category:tt {
714 $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
716 define_queries_inner! { <$tcx>
717 $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
722 macro_rules! define_queries_inner {
724 $($(#[$attr:meta])* category<$category:tt>
725 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
728 use rustc_data_structures::sharded::Sharded;
730 rustc_data_structures::stable_hasher::HashStable,
731 rustc_data_structures::stable_hasher::StableHasher,
732 ich::StableHashingContext
734 use rustc_data_structures::profiling::ProfileCategory;
736 define_queries_struct! {
738 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
741 impl<$tcx> Queries<$tcx> {
743 providers: IndexVec<CrateNum, Providers<$tcx>>,
744 fallback_extern_providers: Providers<$tcx>,
745 on_disk_cache: OnDiskCache<'tcx>,
749 fallback_extern_providers: Box::new(fallback_extern_providers),
751 $($name: Default::default()),*
755 pub fn try_collect_active_jobs(
757 ) -> Option<FxHashMap<QueryJobId, QueryJobInfo<'tcx>>> {
758 let mut jobs = FxHashMap::default();
761 // We use try_lock_shards here since we are called from the
762 // deadlock handler, and this shouldn't be locked.
763 let shards = self.$name.try_lock_shards()?;
764 let shards = shards.iter().enumerate();
765 jobs.extend(shards.flat_map(|(shard_id, shard)| {
766 shard.active.iter().filter_map(move |(k, v)| {
767 if let QueryResult::Started(ref job) = *v {
768 let id = QueryJobId {
770 shard: u16::try_from(shard_id).unwrap(),
772 <queries::$name<'tcx> as QueryAccessors<'tcx>>::dep_kind(),
774 let info = QueryInfo {
776 query: queries::$name::query(k.clone())
778 Some((id, QueryJobInfo { info, job: job.clone() }))
789 pub fn print_stats(&self) {
790 let mut queries = Vec::new();
797 key_type: &'static str,
799 value_type: &'static str,
803 fn stats<'tcx, Q: QueryConfig<'tcx>>(
805 map: &Sharded<QueryCache<'tcx, Q>>,
807 let map = map.lock_shards();
810 #[cfg(debug_assertions)]
811 cache_hits: map.iter().map(|shard| shard.cache_hits).sum(),
812 #[cfg(not(debug_assertions))]
814 key_size: mem::size_of::<Q::Key>(),
815 key_type: type_name::<Q::Key>(),
816 value_size: mem::size_of::<Q::Value>(),
817 value_type: type_name::<Q::Value>(),
818 entry_count: map.iter().map(|shard| shard.results.len()).sum(),
823 queries.push(stats::<queries::$name<'_>>(
829 if cfg!(debug_assertions) {
830 let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
831 let results: usize = queries.iter().map(|s| s.entry_count).sum();
832 println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
835 let mut query_key_sizes = queries.clone();
836 query_key_sizes.sort_by_key(|q| q.key_size);
837 println!("\nLarge query keys:");
838 for q in query_key_sizes.iter().rev()
839 .filter(|q| q.key_size > 8) {
841 " {} - {} x {} - {}",
849 let mut query_value_sizes = queries.clone();
850 query_value_sizes.sort_by_key(|q| q.value_size);
851 println!("\nLarge query values:");
852 for q in query_value_sizes.iter().rev()
853 .filter(|q| q.value_size > 8) {
855 " {} - {} x {} - {}",
863 if cfg!(debug_assertions) {
864 let mut query_cache_hits = queries.clone();
865 query_cache_hits.sort_by_key(|q| q.cache_hits);
866 println!("\nQuery cache hits:");
867 for q in query_cache_hits.iter().rev() {
872 q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
877 let mut query_value_count = queries.clone();
878 query_value_count.sort_by_key(|q| q.entry_count);
879 println!("\nQuery value count:");
880 for q in query_value_count.iter().rev() {
881 println!(" {} - {}", q.name, q.entry_count);
886 #[allow(nonstandard_style)]
887 #[derive(Clone, Debug)]
888 pub enum Query<$tcx> {
889 $($(#[$attr])* $name($K)),*
892 impl<$tcx> Query<$tcx> {
893 pub fn name(&self) -> &'static str {
895 $(Query::$name(_) => stringify!($name),)*
899 pub fn describe(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
900 let (r, name) = match *self {
901 $(Query::$name(key) => {
902 (queries::$name::describe(tcx, key), stringify!($name))
905 if tcx.sess.verbose() {
906 format!("{} [{}]", r, name).into()
912 // FIXME(eddyb) Get more valid `Span`s on queries.
913 pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
914 if !span.is_dummy() {
917 // The `def_span` query is used to calculate `default_span`,
918 // so exit to avoid infinite recursion.
919 if let Query::def_span(..) = *self {
923 $(Query::$name(key) => key.default_span(tcx),)*
928 impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
929 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
930 mem::discriminant(self).hash_stable(hcx, hasher);
932 $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
938 use std::marker::PhantomData;
940 $(#[allow(nonstandard_style)]
941 pub struct $name<$tcx> {
942 data: PhantomData<&$tcx ()>
946 // This module and the functions in it exist only to provide a
947 // predictable symbol name prefix for query providers. This is helpful
948 // for analyzing queries in profilers.
949 pub(super) mod __query_compute {
951 pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
956 $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
960 const NAME: &'static str = stringify!($name);
961 const CATEGORY: ProfileCategory = $category;
964 impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
965 const ANON: bool = is_anon!([$($modifiers)*]);
966 const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
969 fn query(key: Self::Key) -> Query<'tcx> {
974 fn query_cache<'a>(tcx: TyCtxt<$tcx>) -> &'a Sharded<QueryCache<$tcx, Self>> {
980 fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
981 use crate::dep_graph::DepConstructor::*;
983 DepNode::new(tcx, $node(*key))
987 fn dep_kind() -> dep_graph::DepKind {
988 dep_graph::DepKind::$node
992 fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
993 __query_compute::$name(move || {
994 let provider = tcx.queries.providers.get(key.query_crate())
995 // HACK(eddyb) it's possible crates may be loaded after
996 // the query engine is created, and because crate loading
997 // is not yet integrated with the query engine, such crates
998 // would be missing appropriate entries in `providers`.
999 .unwrap_or(&tcx.queries.fallback_extern_providers)
1006 _hcx: &mut StableHashingContext<'_>,
1007 _result: &Self::Value
1008 ) -> Option<Fingerprint> {
1009 hash_result!([$($modifiers)*][_hcx, _result])
1012 fn handle_cycle_error(
1014 error: CycleError<'tcx>
1016 handle_cycle_error!([$($modifiers)*][tcx, error])
1020 #[derive(Copy, Clone)]
1021 pub struct TyCtxtEnsure<'tcx> {
1022 pub tcx: TyCtxt<'tcx>,
1025 impl TyCtxtEnsure<$tcx> {
1028 pub fn $name(self, key: $K) {
1029 self.tcx.ensure_query::<queries::$name<'_>>(key)
1033 #[derive(Copy, Clone)]
1034 pub struct TyCtxtAt<'tcx> {
1035 pub tcx: TyCtxt<'tcx>,
1039 impl Deref for TyCtxtAt<'tcx> {
1040 type Target = TyCtxt<'tcx>;
1042 fn deref(&self) -> &Self::Target {
1048 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1049 /// are executed instead of just returing their results.
1051 pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1057 /// Returns a transparent wrapper for `TyCtxt` which uses
1058 /// `span` as the location of queries performed through it.
1060 pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1069 pub fn $name(self, key: $K) -> $V {
1070 self.at(DUMMY_SP).$name(key)
1073 /// All self-profiling events generated by the query engine use
1074 /// virtual `StringId`s for their `event_id`. This method makes all
1075 /// those virtual `StringId`s point to actual strings.
1077 /// If we are recording only summary data, the ids will point to
1078 /// just the query names. If we are recording query keys too, we
1079 /// allocate the corresponding strings here.
1080 pub fn alloc_self_profile_query_strings(self) {
1081 use crate::ty::query::profiling_support::{
1082 alloc_self_profile_query_strings_for_query_cache,
1083 QueryKeyStringCache,
1086 if !self.prof.enabled() {
1090 let mut string_cache = QueryKeyStringCache::new();
1093 alloc_self_profile_query_strings_for_query_cache(
1096 &self.queries.$name,
1103 impl TyCtxtAt<$tcx> {
1106 pub fn $name(self, key: $K) -> $V {
1107 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1111 define_provider_struct! {
1113 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1116 impl<$tcx> Copy for Providers<$tcx> {}
1117 impl<$tcx> Clone for Providers<$tcx> {
1118 fn clone(&self) -> Self { *self }
1123 macro_rules! define_queries_struct {
1125 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1126 pub struct Queries<$tcx> {
1127 /// This provides access to the incrimental comilation on-disk cache for query results.
1128 /// Do not access this directly. It is only meant to be used by
1129 /// `DepGraph::try_mark_green()` and the query infrastructure.
1130 pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1132 providers: IndexVec<CrateNum, Providers<$tcx>>,
1133 fallback_extern_providers: Box<Providers<$tcx>>,
1135 $($(#[$attr])* $name: Sharded<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1140 macro_rules! define_provider_struct {
1142 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1143 pub struct Providers<$tcx> {
1144 $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1147 impl<$tcx> Default for Providers<$tcx> {
1148 fn default() -> Self {
1149 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1150 bug!("`tcx.{}({:?})` unsupported by its crate",
1151 stringify!($name), key);
1153 Providers { $($name),* }
1159 /// The red/green evaluation system will try to mark a specific DepNode in the
1160 /// dependency graph as green by recursively trying to mark the dependencies of
1161 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
1162 /// where we don't know if it is red or green and we therefore actually have
1163 /// to recompute its value in order to find out. Since the only piece of
1164 /// information that we have at that point is the `DepNode` we are trying to
1165 /// re-evaluate, we need some way to re-run a query from just that. This is what
1166 /// `force_from_dep_node()` implements.
1168 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
1169 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1170 /// is usually constructed by computing a stable hash of the query-key that the
1171 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
1172 /// back from hash to query-key (since hash functions are not reversible). For
1173 /// this reason `force_from_dep_node()` is expected to fail from time to time
1174 /// because we just cannot find out, from the `DepNode` alone, what the
1175 /// corresponding query-key is and therefore cannot re-run the query.
1177 /// The system deals with this case letting `try_mark_green` fail which forces
1178 /// the root query to be re-evaluated.
1180 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
1181 /// Fortunately, we can use some contextual information that will allow us to
1182 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1183 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1184 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1185 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1186 /// everything we need to re-run the query.
1188 /// Take the `mir_validated` query as an example. Like many other queries, it
1189 /// just has a single parameter: the `DefId` of the item it will compute the
1190 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1191 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1192 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1193 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1195 /// When you implement a new query, it will likely have a corresponding new
1196 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1197 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1198 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1199 /// add it to the "We don't have enough information to reconstruct..." group in
1200 /// the match below.
1201 pub fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: &DepNode) -> bool {
1202 use crate::dep_graph::RecoverKey;
1204 // We must avoid ever having to call `force_from_dep_node()` for a
1205 // `DepNode::codegen_unit`:
1206 // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
1207 // would always end up having to evaluate the first caller of the
1208 // `codegen_unit` query that *is* reconstructible. This might very well be
1209 // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1210 // to re-trigger calling the `codegen_unit` query with the right key. At
1211 // that point we would already have re-done all the work we are trying to
1212 // avoid doing in the first place.
1213 // The solution is simple: Just explicitly call the `codegen_unit` query for
1214 // each CGU, right after partitioning. This way `try_mark_green` will always
1215 // hit the cache instead of having to go through `force_from_dep_node`.
1216 // This assertion makes sure, we actually keep applying the solution above.
1218 dep_node.kind != DepKind::codegen_unit,
1219 "calling force_from_dep_node() on DepKind::codegen_unit"
1222 if !dep_node.kind.can_reconstruct_query_key() {
1226 rustc_dep_node_force!([dep_node, tcx]
1227 // These are inputs that are expected to be pre-allocated and that
1228 // should therefore always be red or green already.
1229 DepKind::AllLocalTraitImpls |
1230 DepKind::CrateMetadata |
1234 // These are anonymous nodes.
1235 DepKind::TraitSelect |
1237 // We don't have enough information to reconstruct the query key of
1239 DepKind::CompileCodegenUnit => {
1240 bug!("force_from_dep_node: encountered {:?}", dep_node)
1243 DepKind::Analysis => {
1244 let def_id = if let Some(def_id) = dep_node.extract_def_id(tcx) {
1247 // Return from the whole function.
1250 tcx.force_query::<crate::ty::query::queries::analysis<'_>>(