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};
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, Lrc};
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};
28 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
29 pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
30 pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
31 #[cfg(debug_assertions)]
32 pub(super) cache_hits: usize,
35 pub(super) struct QueryValue<T> {
37 pub(super) index: DepNodeIndex,
40 impl<T> QueryValue<T> {
41 pub(super) fn new(value: T, dep_node_index: DepNodeIndex) -> QueryValue<T> {
42 QueryValue { value, index: dep_node_index }
46 /// Indicates the state of a query for a given key in a query map.
47 pub(super) enum QueryResult<'tcx> {
48 /// An already executing query. The query job can be used to await for its completion.
49 Started(Lrc<QueryJob<'tcx>>),
51 /// The query panicked. Queries trying to wait on this will raise a fatal error or
56 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
57 fn default() -> QueryCache<'tcx, M> {
59 results: FxHashMap::default(),
60 active: FxHashMap::default(),
61 #[cfg(debug_assertions)]
67 /// A type representing the responsibility to execute the job in the `job` field.
68 /// This will poison the relevant query if dropped.
69 pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx>> {
70 cache: &'a Sharded<QueryCache<'tcx, Q>>,
72 job: Lrc<QueryJob<'tcx>>,
75 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
76 /// Either gets a `JobOwner` corresponding the query, allowing us to
77 /// start executing the query, or returns with the result of the query.
78 /// If the query is executing elsewhere, this will wait for it.
79 /// If the query panicked, this will silently panic.
81 /// This function is inlined because that results in a noticeable speed-up
82 /// for some compile-time benchmarks.
84 pub(super) fn try_get(tcx: TyCtxt<'tcx>, span: Span, key: &Q::Key) -> TryGetJob<'a, 'tcx, Q> {
85 // Handling the `query_blocked_prof_timer` is a bit weird because of the
86 // control flow in this function: Blocking is implemented by
87 // awaiting a running job and, once that is done, entering the loop below
88 // again from the top. In that second iteration we will hit the
89 // cache which provides us with the information we need for
90 // finishing the "query-blocked" event.
92 // We thus allocate `query_blocked_prof_timer` outside the loop,
93 // initialize it during the first iteration and finish it during the
95 #[cfg(parallel_compiler)]
96 let mut query_blocked_prof_timer: Option<TimingGuard<'_>> = None;
98 let cache = Q::query_cache(tcx);
100 // We compute the key's hash once and then use it for both the
101 // shard lookup and the hashmap lookup. This relies on the fact
102 // that both of them use `FxHasher`.
103 let mut state = FxHasher::default();
104 key.hash(&mut state);
105 let key_hash = state.finish();
107 let mut lock = cache.get_shard_by_hash(key_hash).lock();
108 if let Some((_, value)) =
109 lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
111 if unlikely!(tcx.prof.enabled()) {
112 tcx.prof.query_cache_hit(value.index.into());
114 #[cfg(parallel_compiler)]
116 if let Some(prof_timer) = query_blocked_prof_timer.take() {
117 prof_timer.finish_with_query_invocation_id(value.index.into());
122 let result = (value.value.clone(), value.index);
123 #[cfg(debug_assertions)]
125 lock.cache_hits += 1;
127 return TryGetJob::JobCompleted(result);
130 let job = match lock.active.entry((*key).clone()) {
131 Entry::Occupied(entry) => {
133 QueryResult::Started(ref job) => {
134 // For parallel queries, we'll block and wait until the query running
135 // in another thread has completed. Record how long we wait in the
137 #[cfg(parallel_compiler)]
139 query_blocked_prof_timer = Some(tcx.prof.query_blocked());
144 QueryResult::Poisoned => FatalError.raise(),
147 Entry::Vacant(entry) => {
148 // No job entry for this query. Return a new one to be started later.
149 return tls::with_related_context(tcx, |icx| {
150 // Create the `parent` variable before `info`. This allows LLVM
151 // to elide the move of `info`
152 let parent = icx.query.clone();
153 let info = QueryInfo { span, query: Q::query(key.clone()) };
154 let job = Lrc::new(QueryJob::new(info, parent));
155 let owner = JobOwner { cache, job: job.clone(), key: (*key).clone() };
156 entry.insert(QueryResult::Started(job));
157 TryGetJob::NotYetStarted(owner)
163 // If we are single-threaded we know that we have cycle error,
164 // so we just return the error.
165 #[cfg(not(parallel_compiler))]
166 return TryGetJob::Cycle(cold_path(|| {
167 Q::handle_cycle_error(tcx, job.find_cycle_in_stack(tcx, span))
170 // With parallel queries we might just have to wait on some other
172 #[cfg(parallel_compiler)]
174 let result = job.r#await(tcx, span);
176 if let Err(cycle) = result {
177 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
183 /// Completes the query by updating the query cache with the `result`,
184 /// signals the waiter and forgets the JobOwner, so it won't poison the query
186 pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
187 // We can move out of `self` here because we `mem::forget` it below
188 let key = unsafe { ptr::read(&self.key) };
189 let job = unsafe { ptr::read(&self.job) };
190 let cache = self.cache;
192 // Forget ourself so our destructor won't poison the query
195 let value = QueryValue::new(result.clone(), dep_node_index);
197 let mut lock = cache.get_shard_by_value(&key).lock();
198 lock.active.remove(&key);
199 lock.results.insert(key, value);
202 job.signal_complete();
207 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
209 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
211 let diagnostics = Lock::new(ThinVec::new());
212 let result = f(Some(&diagnostics));
213 (result, diagnostics.into_inner())
216 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
220 // Poison the query so jobs waiting on it panic.
221 let shard = self.cache.get_shard_by_value(&self.key);
222 shard.lock().active.insert(self.key.clone(), QueryResult::Poisoned);
223 // Also signal the completion of the job, so waiters
224 // will continue execution.
225 self.job.signal_complete();
230 pub struct CycleError<'tcx> {
231 /// The query and related span that uses the cycle.
232 pub(super) usage: Option<(Span, Query<'tcx>)>,
233 pub(super) cycle: Vec<QueryInfo<'tcx>>,
236 /// The result of `try_get_lock`.
237 pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx>> {
238 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
239 NotYetStarted(JobOwner<'a, 'tcx, D>),
241 /// The query was already completed.
242 /// Returns the result of the query and its dep-node index
243 /// if it succeeded or a cycle error if it failed.
244 JobCompleted((D::Value, DepNodeIndex)),
246 /// Trying to execute the query resulted in a cycle.
250 impl<'tcx> TyCtxt<'tcx> {
251 /// Executes a job by changing the `ImplicitCtxt` to point to the
252 /// new query job while it executes. It returns the diagnostics
253 /// captured during execution and the actual result.
255 pub(super) fn start_query<F, R>(
257 job: Lrc<QueryJob<'tcx>>,
258 diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
262 F: FnOnce(TyCtxt<'tcx>) -> R,
264 // The `TyCtxt` stored in TLS has the same global interner lifetime
265 // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
266 // when accessing the `ImplicitCtxt`.
267 tls::with_related_context(self, move |current_icx| {
268 // Update the `ImplicitCtxt` to point to our new query job.
269 let new_icx = tls::ImplicitCtxt {
273 layout_depth: current_icx.layout_depth,
274 task_deps: current_icx.task_deps,
277 // Use the `ImplicitCtxt` while we execute the query.
278 tls::enter_context(&new_icx, |_| compute(self))
284 pub(super) fn report_cycle(
286 CycleError { usage, cycle: stack }: CycleError<'tcx>,
287 ) -> DiagnosticBuilder<'tcx> {
288 assert!(!stack.is_empty());
290 let fix_span = |span: Span, query: &Query<'tcx>| {
291 self.sess.source_map().def_span(query.default_span(self, span))
294 // Disable naming impls with types in this path, since that
295 // sometimes cycles itself, leading to extra cycle errors.
296 // (And cycle errors around impls tend to occur during the
297 // collect/coherence phases anyhow.)
298 ty::print::with_forced_impl_filename_line(|| {
299 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
300 let mut err = struct_span_err!(
304 "cycle detected when {}",
305 stack[0].query.describe(self)
308 for i in 1..stack.len() {
309 let query = &stack[i].query;
310 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
311 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
315 "...which again requires {}, completing the cycle",
316 stack[0].query.describe(self)
319 if let Some((span, query)) = usage {
321 fix_span(span, &query),
322 &format!("cycle used when {}", query.describe(self)),
330 pub fn try_print_query_stack(handler: &Handler) {
331 eprintln!("query stack during panic:");
333 // Be careful reyling on global state here: this code is called from
334 // a panic hook, which means that the global `Handler` may be in a weird
335 // state if it was responsible for triggering the panic.
336 tls::with_context_opt(|icx| {
337 if let Some(icx) = icx {
338 let mut current_query = icx.query.clone();
341 while let Some(query) = current_query {
342 let mut diag = Diagnostic::new(
347 query.info.query.name(),
348 query.info.query.describe(icx.tcx)
351 diag.span = icx.tcx.sess.source_map().def_span(query.info.span).into();
352 handler.force_print_diagnostic(diag);
354 current_query = query.parent.clone();
360 eprintln!("end of query stack");
364 pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
365 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
367 let job = match JobOwner::try_get(self, span, &key) {
368 TryGetJob::NotYetStarted(job) => job,
369 TryGetJob::Cycle(result) => return result,
370 TryGetJob::JobCompleted((v, index)) => {
371 self.dep_graph.read_index(index);
376 // Fast path for when incr. comp. is off. `to_dep_node` is
377 // expensive for some `DepKind`s.
378 if !self.dep_graph.is_fully_enabled() {
379 let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
380 return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
384 let prof_timer = self.prof.query_provider();
386 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
387 self.start_query(job.job.clone(), diagnostics, |tcx| {
388 tcx.dep_graph.with_anon_task(Q::dep_kind(), || Q::compute(tcx, key))
392 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
394 self.dep_graph.read_index(dep_node_index);
396 if unlikely!(!diagnostics.is_empty()) {
399 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
402 job.complete(&result, dep_node_index);
407 let dep_node = Q::to_dep_node(self, &key);
410 // The diagnostics for this query will be
411 // promoted to the current session during
412 // `try_mark_green()`, so we can ignore them here.
413 let loaded = self.start_query(job.job.clone(), None, |tcx| {
414 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
415 marked.map(|(prev_dep_node_index, dep_node_index)| {
417 tcx.load_from_disk_and_cache_in_memory::<Q>(
427 if let Some((result, dep_node_index)) = loaded {
428 job.complete(&result, dep_node_index);
433 let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
434 self.dep_graph.read_index(dep_node_index);
438 fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'tcx>>(
441 prev_dep_node_index: SerializedDepNodeIndex,
442 dep_node_index: DepNodeIndex,
445 // Note this function can be called concurrently from the same query
446 // We must ensure that this is handled correctly.
448 debug_assert!(self.dep_graph.is_green(dep_node));
450 // First we try to load the result from the on-disk cache.
451 let result = if Q::cache_on_disk(self, key.clone(), None)
452 && self.sess.opts.debugging_opts.incremental_queries
454 let prof_timer = self.prof.incr_cache_loading();
455 let result = Q::try_load_from_disk(self, prev_dep_node_index);
456 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
458 // We always expect to find a cached result for things that
459 // can be forced from `DepNode`.
461 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
462 "missing on-disk cache entry for {:?}",
467 // Some things are never cached on disk.
471 let result = if let Some(result) = result {
474 // We could not load a result from the on-disk cache, so
476 let prof_timer = self.prof.query_provider();
478 // The dep-graph for this computation is already in-place.
479 let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
481 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
486 // If `-Zincremental-verify-ich` is specified, re-hash results from
487 // the cache and make sure that they have the expected fingerprint.
488 if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
489 self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
497 fn incremental_verify_ich<Q: QueryDescription<'tcx>>(
501 dep_node_index: DepNodeIndex,
503 use crate::ich::Fingerprint;
506 Some(self.dep_graph.fingerprint_of(dep_node_index))
507 == self.dep_graph.prev_fingerprint_of(dep_node),
508 "fingerprint for green query instance not loaded from cache: {:?}",
512 debug!("BEGIN verify_ich({:?})", dep_node);
513 let mut hcx = self.create_stable_hashing_context();
515 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
516 debug!("END verify_ich({:?})", dep_node);
518 let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
520 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
524 fn force_query_with_job<Q: QueryDescription<'tcx>>(
527 job: JobOwner<'_, 'tcx, Q>,
529 ) -> (Q::Value, DepNodeIndex) {
530 // If the following assertion triggers, it can have two reasons:
531 // 1. Something is wrong with DepNode creation, either here or
532 // in `DepGraph::try_mark_green()`.
533 // 2. Two distinct query keys get mapped to the same `DepNode`
534 // (see for example #48923).
536 !self.dep_graph.dep_node_exists(&dep_node),
537 "forcing query with already existing `DepNode`\n\
544 let prof_timer = self.prof.query_provider();
546 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
547 self.start_query(job.job.clone(), diagnostics, |tcx| {
549 tcx.dep_graph.with_eval_always_task(
557 tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
562 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
564 if unlikely!(!diagnostics.is_empty()) {
565 if dep_node.kind != crate::dep_graph::DepKind::Null {
566 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
570 job.complete(&result, dep_node_index);
572 (result, dep_node_index)
575 /// Ensure that either this query has all green inputs or been executed.
576 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
578 /// This function is particularly useful when executing passes for their
579 /// side-effects -- e.g., in order to report errors for erroneous programs.
581 /// Note: The optimization is only available during incr. comp.
582 pub(super) fn ensure_query<Q: QueryDescription<'tcx>>(self, key: Q::Key) -> () {
584 let _ = self.get_query::<Q>(DUMMY_SP, key);
588 // Ensuring an anonymous query makes no sense
591 let dep_node = Q::to_dep_node(self, &key);
593 match self.dep_graph.try_mark_green_and_read(self, &dep_node) {
595 // A None return from `try_mark_green_and_read` means that this is either
596 // a new dep node or that the dep node has already been marked red.
597 // Either way, we can't call `dep_graph.read()` as we don't have the
598 // DepNodeIndex. We must invoke the query itself. The performance cost
599 // this introduces should be negligible as we'll immediately hit the
600 // in-memory cache, or another query down the line will.
601 let _ = self.get_query::<Q>(DUMMY_SP, key);
603 Some((_, dep_node_index)) => {
604 self.prof.query_cache_hit(dep_node_index.into());
610 fn force_query<Q: QueryDescription<'tcx>>(self, key: Q::Key, span: Span, dep_node: DepNode) {
611 // We may be concurrently trying both execute and force a query.
612 // Ensure that only one of them runs the query.
613 let job = match JobOwner::try_get(self, span, &key) {
614 TryGetJob::NotYetStarted(job) => job,
615 TryGetJob::Cycle(_) | TryGetJob::JobCompleted(_) => return,
617 self.force_query_with_job::<Q>(key, job, dep_node);
621 macro_rules! handle_cycle_error {
622 ([][$tcx: expr, $error:expr]) => {{
623 $tcx.report_cycle($error).emit();
624 Value::from_cycle_error($tcx)
626 ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
627 $tcx.report_cycle($error).emit();
628 $tcx.sess.abort_if_errors();
631 ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
632 $tcx.report_cycle($error).delay_as_bug();
633 Value::from_cycle_error($tcx)
635 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
636 handle_cycle_error!([$($modifiers),*][$($args)*])
640 macro_rules! is_anon {
644 ([anon$(, $modifiers:ident)*]) => {{
647 ([$other:ident$(, $modifiers:ident)*]) => {
648 is_anon!([$($modifiers),*])
652 macro_rules! is_eval_always {
656 ([eval_always$(, $modifiers:ident)*]) => {{
659 ([$other:ident$(, $modifiers:ident)*]) => {
660 is_eval_always!([$($modifiers),*])
664 macro_rules! hash_result {
665 ([][$hcx:expr, $result:expr]) => {{
666 dep_graph::hash_result($hcx, &$result)
668 ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
671 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
672 hash_result!([$($modifiers),*][$($args)*])
676 macro_rules! define_queries {
677 (<$tcx:tt> $($category:tt {
678 $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
680 define_queries_inner! { <$tcx>
681 $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
686 macro_rules! define_queries_inner {
688 $($(#[$attr:meta])* category<$category:tt>
689 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
692 use rustc_data_structures::sharded::Sharded;
694 rustc_data_structures::stable_hasher::HashStable,
695 rustc_data_structures::stable_hasher::StableHasher,
696 ich::StableHashingContext
698 use rustc_data_structures::profiling::ProfileCategory;
700 define_queries_struct! {
702 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
705 impl<$tcx> Queries<$tcx> {
707 providers: IndexVec<CrateNum, Providers<$tcx>>,
708 fallback_extern_providers: Providers<$tcx>,
709 on_disk_cache: OnDiskCache<'tcx>,
713 fallback_extern_providers: Box::new(fallback_extern_providers),
715 $($name: Default::default()),*
719 #[cfg(parallel_compiler)]
720 pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
721 let mut jobs = Vec::new();
723 // We use try_lock_shards here since we are only called from the
724 // deadlock handler, and this shouldn't be locked.
726 let shards = self.$name.try_lock_shards().unwrap();
727 jobs.extend(shards.iter().flat_map(|shard| shard.active.values().filter_map(|v|
728 if let QueryResult::Started(ref job) = *v {
739 pub fn print_stats(&self) {
740 let mut queries = Vec::new();
747 key_type: &'static str,
749 value_type: &'static str,
753 fn stats<'tcx, Q: QueryConfig<'tcx>>(
755 map: &Sharded<QueryCache<'tcx, Q>>,
757 let map = map.lock_shards();
760 #[cfg(debug_assertions)]
761 cache_hits: map.iter().map(|shard| shard.cache_hits).sum(),
762 #[cfg(not(debug_assertions))]
764 key_size: mem::size_of::<Q::Key>(),
765 key_type: type_name::<Q::Key>(),
766 value_size: mem::size_of::<Q::Value>(),
767 value_type: type_name::<Q::Value>(),
768 entry_count: map.iter().map(|shard| shard.results.len()).sum(),
773 queries.push(stats::<queries::$name<'_>>(
779 if cfg!(debug_assertions) {
780 let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
781 let results: usize = queries.iter().map(|s| s.entry_count).sum();
782 println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
785 let mut query_key_sizes = queries.clone();
786 query_key_sizes.sort_by_key(|q| q.key_size);
787 println!("\nLarge query keys:");
788 for q in query_key_sizes.iter().rev()
789 .filter(|q| q.key_size > 8) {
791 " {} - {} x {} - {}",
799 let mut query_value_sizes = queries.clone();
800 query_value_sizes.sort_by_key(|q| q.value_size);
801 println!("\nLarge query values:");
802 for q in query_value_sizes.iter().rev()
803 .filter(|q| q.value_size > 8) {
805 " {} - {} x {} - {}",
813 if cfg!(debug_assertions) {
814 let mut query_cache_hits = queries.clone();
815 query_cache_hits.sort_by_key(|q| q.cache_hits);
816 println!("\nQuery cache hits:");
817 for q in query_cache_hits.iter().rev() {
822 q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
827 let mut query_value_count = queries.clone();
828 query_value_count.sort_by_key(|q| q.entry_count);
829 println!("\nQuery value count:");
830 for q in query_value_count.iter().rev() {
831 println!(" {} - {}", q.name, q.entry_count);
836 #[allow(nonstandard_style)]
837 #[derive(Clone, Debug)]
838 pub enum Query<$tcx> {
839 $($(#[$attr])* $name($K)),*
842 impl<$tcx> Query<$tcx> {
843 pub fn name(&self) -> &'static str {
845 $(Query::$name(_) => stringify!($name),)*
849 pub fn describe(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
850 let (r, name) = match *self {
851 $(Query::$name(key) => {
852 (queries::$name::describe(tcx, key), stringify!($name))
855 if tcx.sess.verbose() {
856 format!("{} [{}]", r, name).into()
862 // FIXME(eddyb) Get more valid `Span`s on queries.
863 pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
864 if !span.is_dummy() {
867 // The `def_span` query is used to calculate `default_span`,
868 // so exit to avoid infinite recursion.
869 if let Query::def_span(..) = *self {
873 $(Query::$name(key) => key.default_span(tcx),)*
878 impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
879 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
880 mem::discriminant(self).hash_stable(hcx, hasher);
882 $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
888 use std::marker::PhantomData;
890 $(#[allow(nonstandard_style)]
891 pub struct $name<$tcx> {
892 data: PhantomData<&$tcx ()>
896 // This module and the functions in it exist only to provide a
897 // predictable symbol name prefix for query providers. This is helpful
898 // for analyzing queries in profilers.
899 pub(super) mod __query_compute {
901 pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
906 $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
910 const NAME: &'static str = stringify!($name);
911 const CATEGORY: ProfileCategory = $category;
914 impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
915 const ANON: bool = is_anon!([$($modifiers)*]);
916 const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
919 fn query(key: Self::Key) -> Query<'tcx> {
924 fn query_cache<'a>(tcx: TyCtxt<$tcx>) -> &'a Sharded<QueryCache<$tcx, Self>> {
930 fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
931 use crate::dep_graph::DepConstructor::*;
933 DepNode::new(tcx, $node(*key))
937 fn dep_kind() -> dep_graph::DepKind {
938 dep_graph::DepKind::$node
942 fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
943 __query_compute::$name(move || {
944 let provider = tcx.queries.providers.get(key.query_crate())
945 // HACK(eddyb) it's possible crates may be loaded after
946 // the query engine is created, and because crate loading
947 // is not yet integrated with the query engine, such crates
948 // would be missing appropriate entries in `providers`.
949 .unwrap_or(&tcx.queries.fallback_extern_providers)
956 _hcx: &mut StableHashingContext<'_>,
957 _result: &Self::Value
958 ) -> Option<Fingerprint> {
959 hash_result!([$($modifiers)*][_hcx, _result])
962 fn handle_cycle_error(
964 error: CycleError<'tcx>
966 handle_cycle_error!([$($modifiers)*][tcx, error])
970 #[derive(Copy, Clone)]
971 pub struct TyCtxtEnsure<'tcx> {
972 pub tcx: TyCtxt<'tcx>,
975 impl TyCtxtEnsure<$tcx> {
978 pub fn $name(self, key: $K) {
979 self.tcx.ensure_query::<queries::$name<'_>>(key)
983 #[derive(Copy, Clone)]
984 pub struct TyCtxtAt<'tcx> {
985 pub tcx: TyCtxt<'tcx>,
989 impl Deref for TyCtxtAt<'tcx> {
990 type Target = TyCtxt<'tcx>;
992 fn deref(&self) -> &Self::Target {
998 /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
999 /// are executed instead of just returing their results.
1001 pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1007 /// Returns a transparent wrapper for `TyCtxt` which uses
1008 /// `span` as the location of queries performed through it.
1010 pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1019 pub fn $name(self, key: $K) -> $V {
1020 self.at(DUMMY_SP).$name(key)
1023 /// All self-profiling events generated by the query engine use
1024 /// virtual `StringId`s for their `event_id`. This method makes all
1025 /// those virtual `StringId`s point to actual strings.
1027 /// If we are recording only summary data, the ids will point to
1028 /// just the query names. If we are recording query keys too, we
1029 /// allocate the corresponding strings here.
1030 pub fn alloc_self_profile_query_strings(self) {
1031 use crate::ty::query::profiling_support::{
1032 alloc_self_profile_query_strings_for_query_cache,
1033 QueryKeyStringCache,
1036 if !self.prof.enabled() {
1040 let mut string_cache = QueryKeyStringCache::new();
1043 alloc_self_profile_query_strings_for_query_cache(
1046 &self.queries.$name,
1053 impl TyCtxtAt<$tcx> {
1056 pub fn $name(self, key: $K) -> $V {
1057 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1061 define_provider_struct! {
1063 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1066 impl<$tcx> Copy for Providers<$tcx> {}
1067 impl<$tcx> Clone for Providers<$tcx> {
1068 fn clone(&self) -> Self { *self }
1073 macro_rules! define_queries_struct {
1075 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1076 pub struct Queries<$tcx> {
1077 /// This provides access to the incrimental comilation on-disk cache for query results.
1078 /// Do not access this directly. It is only meant to be used by
1079 /// `DepGraph::try_mark_green()` and the query infrastructure.
1080 pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1082 providers: IndexVec<CrateNum, Providers<$tcx>>,
1083 fallback_extern_providers: Box<Providers<$tcx>>,
1085 $($(#[$attr])* $name: Sharded<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1090 macro_rules! define_provider_struct {
1092 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1093 pub struct Providers<$tcx> {
1094 $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1097 impl<$tcx> Default for Providers<$tcx> {
1098 fn default() -> Self {
1099 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1100 bug!("`tcx.{}({:?})` unsupported by its crate",
1101 stringify!($name), key);
1103 Providers { $($name),* }
1109 /// The red/green evaluation system will try to mark a specific DepNode in the
1110 /// dependency graph as green by recursively trying to mark the dependencies of
1111 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
1112 /// where we don't know if it is red or green and we therefore actually have
1113 /// to recompute its value in order to find out. Since the only piece of
1114 /// information that we have at that point is the `DepNode` we are trying to
1115 /// re-evaluate, we need some way to re-run a query from just that. This is what
1116 /// `force_from_dep_node()` implements.
1118 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
1119 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1120 /// is usually constructed by computing a stable hash of the query-key that the
1121 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
1122 /// back from hash to query-key (since hash functions are not reversible). For
1123 /// this reason `force_from_dep_node()` is expected to fail from time to time
1124 /// because we just cannot find out, from the `DepNode` alone, what the
1125 /// corresponding query-key is and therefore cannot re-run the query.
1127 /// The system deals with this case letting `try_mark_green` fail which forces
1128 /// the root query to be re-evaluated.
1130 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
1131 /// Fortunately, we can use some contextual information that will allow us to
1132 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1133 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1134 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1135 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1136 /// everything we need to re-run the query.
1138 /// Take the `mir_validated` query as an example. Like many other queries, it
1139 /// just has a single parameter: the `DefId` of the item it will compute the
1140 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1141 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1142 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1143 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1145 /// When you implement a new query, it will likely have a corresponding new
1146 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1147 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1148 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1149 /// add it to the "We don't have enough information to reconstruct..." group in
1150 /// the match below.
1151 pub fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: &DepNode) -> bool {
1152 use crate::dep_graph::RecoverKey;
1154 // We must avoid ever having to call `force_from_dep_node()` for a
1155 // `DepNode::codegen_unit`:
1156 // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
1157 // would always end up having to evaluate the first caller of the
1158 // `codegen_unit` query that *is* reconstructible. This might very well be
1159 // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1160 // to re-trigger calling the `codegen_unit` query with the right key. At
1161 // that point we would already have re-done all the work we are trying to
1162 // avoid doing in the first place.
1163 // The solution is simple: Just explicitly call the `codegen_unit` query for
1164 // each CGU, right after partitioning. This way `try_mark_green` will always
1165 // hit the cache instead of having to go through `force_from_dep_node`.
1166 // This assertion makes sure, we actually keep applying the solution above.
1168 dep_node.kind != DepKind::codegen_unit,
1169 "calling force_from_dep_node() on DepKind::codegen_unit"
1172 if !dep_node.kind.can_reconstruct_query_key() {
1176 rustc_dep_node_force!([dep_node, tcx]
1177 // These are inputs that are expected to be pre-allocated and that
1178 // should therefore always be red or green already.
1179 DepKind::AllLocalTraitImpls |
1181 DepKind::CrateMetadata |
1185 // These are anonymous nodes.
1186 DepKind::TraitSelect |
1188 // We don't have enough information to reconstruct the query key of
1190 DepKind::CompileCodegenUnit => {
1191 bug!("force_from_dep_node: encountered {:?}", dep_node)
1194 DepKind::Analysis => {
1195 let def_id = if let Some(def_id) = dep_node.extract_def_id(tcx) {
1198 // Return from the whole function.
1201 tcx.force_query::<crate::ty::query::queries::analysis<'_>>(