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};
6 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
7 use crate::query::caches::QueryCache;
8 use crate::query::config::{QueryDescription, QueryVtable, QueryVtableExt};
9 use crate::query::job::{QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryShardJobId};
10 use crate::query::{QueryContext, QueryMap};
12 #[cfg(not(parallel_compiler))]
13 use rustc_data_structures::cold_path;
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc_data_structures::fx::{FxHashMap, FxHasher};
16 use rustc_data_structures::sharded::Sharded;
17 use rustc_data_structures::sync::{Lock, LockGuard};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_errors::{Diagnostic, FatalError};
21 use std::collections::hash_map::Entry;
23 use std::hash::{Hash, Hasher};
25 use std::num::NonZeroU32;
27 #[cfg(debug_assertions)]
28 use std::sync::atomic::{AtomicUsize, Ordering};
30 pub(super) struct QueryStateShard<D, Q, K, C> {
32 active: FxHashMap<K, QueryResult<D, Q>>,
34 /// Used to generate unique ids for active jobs.
38 impl<D, Q, K, C: Default> Default for QueryStateShard<D, Q, K, C> {
39 fn default() -> QueryStateShard<D, Q, K, C> {
40 QueryStateShard { cache: Default::default(), active: Default::default(), jobs: 0 }
44 pub struct QueryState<D, Q, C: QueryCache> {
46 shards: Sharded<QueryStateShard<D, Q, C::Key, C::Sharded>>,
47 #[cfg(debug_assertions)]
48 pub cache_hits: AtomicUsize,
51 impl<D, Q, C: QueryCache> QueryState<D, Q, C> {
52 pub(super) fn get_lookup<'tcx>(
55 ) -> QueryLookup<'tcx, D, Q, C::Key, C::Sharded> {
56 // We compute the key's hash once and then use it for both the
57 // shard lookup and the hashmap lookup. This relies on the fact
58 // that both of them use `FxHasher`.
59 let mut hasher = FxHasher::default();
60 key.hash(&mut hasher);
61 let key_hash = hasher.finish();
63 let shard = self.shards.get_shard_index_by_hash(key_hash);
64 let lock = self.shards.get_shard_by_index(shard).lock();
65 QueryLookup { key_hash, shard, lock }
69 /// Indicates the state of a query for a given key in a query map.
70 enum QueryResult<D, Q> {
71 /// An already executing query. The query job can be used to await for its completion.
72 Started(QueryJob<D, Q>),
74 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
79 impl<D, Q, C> QueryState<D, Q, C>
81 D: Copy + Clone + Eq + Hash,
85 pub fn iter_results<R>(
87 f: impl for<'a> FnOnce(
88 Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
91 self.cache.iter(&self.shards, |shard| &mut shard.cache, f)
94 pub fn all_inactive(&self) -> bool {
95 let shards = self.shards.lock_shards();
96 shards.iter().all(|shard| shard.active.is_empty())
99 pub fn try_collect_active_jobs(
102 make_query: fn(C::Key) -> Q,
103 jobs: &mut QueryMap<D, Q>,
105 // We use try_lock_shards here since we are called from the
106 // deadlock handler, and this shouldn't be locked.
107 let shards = self.shards.try_lock_shards()?;
108 let shards = shards.iter().enumerate();
109 jobs.extend(shards.flat_map(|(shard_id, shard)| {
110 shard.active.iter().filter_map(move |(k, v)| {
111 if let QueryResult::Started(ref job) = *v {
112 let id = QueryJobId::new(job.id, shard_id, kind);
113 let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
114 Some((id, QueryJobInfo { info, job: job.clone() }))
125 impl<D, Q, C: QueryCache> Default for QueryState<D, Q, C> {
126 fn default() -> QueryState<D, Q, C> {
129 shards: Default::default(),
130 #[cfg(debug_assertions)]
131 cache_hits: AtomicUsize::new(0),
136 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
137 pub struct QueryLookup<'tcx, D, Q, K, C> {
138 pub(super) key_hash: u64,
140 pub(super) lock: LockGuard<'tcx, QueryStateShard<D, Q, K, C>>,
143 /// A type representing the responsibility to execute the job in the `job` field.
144 /// This will poison the relevant query if dropped.
145 struct JobOwner<'tcx, D, Q, C>
147 D: Copy + Clone + Eq + Hash,
151 state: &'tcx QueryState<D, Q, C>,
156 impl<'tcx, D, Q, C> JobOwner<'tcx, D, Q, C>
158 D: Copy + Clone + Eq + Hash,
162 /// Either gets a `JobOwner` corresponding the query, allowing us to
163 /// start executing the query, or returns with the result of the query.
164 /// This function assumes that `try_get_cached` is already called and returned `lookup`.
165 /// If the query is executing elsewhere, this will wait for it and return the result.
166 /// If the query panicked, this will silently panic.
168 /// This function is inlined because that results in a noticeable speed-up
169 /// for some compile-time benchmarks.
171 fn try_start<'a, 'b, CTX>(
173 state: &'b QueryState<CTX::DepKind, CTX::Query, C>,
176 mut lookup: QueryLookup<'a, CTX::DepKind, CTX::Query, C::Key, C::Sharded>,
177 query: &QueryVtable<CTX, C::Key, C::Value>,
178 ) -> TryGetJob<'b, CTX::DepKind, CTX::Query, C>
182 let lock = &mut *lookup.lock;
184 let (latch, mut _query_blocked_prof_timer) = match lock.active.entry((*key).clone()) {
185 Entry::Occupied(mut entry) => {
186 match entry.get_mut() {
187 QueryResult::Started(job) => {
188 // For parallel queries, we'll block and wait until the query running
189 // in another thread has completed. Record how long we wait in the
191 let _query_blocked_prof_timer = if cfg!(parallel_compiler) {
192 Some(tcx.profiler().query_blocked())
197 // Create the id of the job we're waiting for
198 let id = QueryJobId::new(job.id, lookup.shard, query.dep_kind);
200 (job.latch(id), _query_blocked_prof_timer)
202 QueryResult::Poisoned => FatalError.raise(),
205 Entry::Vacant(entry) => {
206 // No job entry for this query. Return a new one to be started later.
208 // Generate an id unique within this shard.
209 let id = lock.jobs.checked_add(1).unwrap();
211 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
213 let global_id = QueryJobId::new(id, lookup.shard, query.dep_kind);
215 let job = tcx.current_query_job();
216 let job = QueryJob::new(id, span, job);
218 entry.insert(QueryResult::Started(job));
220 let owner = JobOwner { state, id: global_id, key: (*key).clone() };
221 return TryGetJob::NotYetStarted(owner);
224 mem::drop(lookup.lock);
226 // If we are single-threaded we know that we have cycle error,
227 // so we just return the error.
228 #[cfg(not(parallel_compiler))]
229 return TryGetJob::Cycle(cold_path(|| {
230 let error: CycleError<CTX::Query> = latch.find_cycle_in_stack(
231 tcx.try_collect_active_jobs().unwrap(),
232 &tcx.current_query_job(),
235 let value = query.handle_cycle_error(tcx, error);
236 state.cache.store_nocache(value)
239 // With parallel queries we might just have to wait on some other
241 #[cfg(parallel_compiler)]
243 let result = latch.wait_on(tcx.current_query_job(), span);
245 if let Err(cycle) = result {
246 let value = query.handle_cycle_error(tcx, cycle);
247 let value = state.cache.store_nocache(value);
248 return TryGetJob::Cycle(value);
251 let cached = try_get_cached(
255 |value, index| (value.clone(), index),
256 |_, _| panic!("value must be in cache after waiting"),
259 if let Some(prof_timer) = _query_blocked_prof_timer.take() {
260 prof_timer.finish_with_query_invocation_id(cached.1.into());
263 return TryGetJob::JobCompleted(cached);
267 /// Completes the query by updating the query cache with the `result`,
268 /// signals the waiter and forgets the JobOwner, so it won't poison the query
269 fn complete(self, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored {
270 // We can move out of `self` here because we `mem::forget` it below
271 let key = unsafe { ptr::read(&self.key) };
272 let state = self.state;
274 // Forget ourself so our destructor won't poison the query
277 let (job, result) = {
278 let mut lock = state.shards.get_shard_by_value(&key).lock();
279 let job = match lock.active.remove(&key).unwrap() {
280 QueryResult::Started(job) => job,
281 QueryResult::Poisoned => panic!(),
283 let result = state.cache.complete(&mut lock.cache, key, result, dep_node_index);
287 job.signal_complete();
292 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
294 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
296 let diagnostics = Lock::new(ThinVec::new());
297 let result = f(Some(&diagnostics));
298 (result, diagnostics.into_inner())
301 impl<'tcx, D, Q, C> Drop for JobOwner<'tcx, D, Q, C>
303 D: Copy + Clone + Eq + Hash,
310 // Poison the query so jobs waiting on it panic.
311 let state = self.state;
312 let shard = state.shards.get_shard_by_value(&self.key);
314 let mut shard = shard.lock();
315 let job = match shard.active.remove(&self.key).unwrap() {
316 QueryResult::Started(job) => job,
317 QueryResult::Poisoned => panic!(),
319 shard.active.insert(self.key.clone(), QueryResult::Poisoned);
322 // Also signal the completion of the job, so waiters
323 // will continue execution.
324 job.signal_complete();
329 pub struct CycleError<Q> {
330 /// The query and related span that uses the cycle.
331 pub usage: Option<(Span, Q)>,
332 pub cycle: Vec<QueryInfo<Q>>,
335 /// The result of `try_start`.
336 enum TryGetJob<'tcx, D, Q, C>
338 D: Copy + Clone + Eq + Hash,
342 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
343 NotYetStarted(JobOwner<'tcx, D, Q, C>),
345 /// The query was already completed.
346 /// Returns the result of the query and its dep-node index
347 /// if it succeeded or a cycle error if it failed.
348 #[cfg(parallel_compiler)]
349 JobCompleted((C::Stored, DepNodeIndex)),
351 /// Trying to execute the query resulted in a cycle.
355 /// Checks if the query is already computed and in the cache.
356 /// It returns the shard index and a lock guard to the shard,
357 /// which will be used if the query is not in the cache and we need
359 fn try_get_cached<CTX, C, R, OnHit, OnMiss>(
361 state: &QueryState<CTX::DepKind, CTX::Query, C>,
363 // `on_hit` can be called while holding a lock to the query cache
370 OnHit: FnOnce(&C::Stored, DepNodeIndex) -> R,
371 OnMiss: FnOnce(C::Key, QueryLookup<'_, CTX::DepKind, CTX::Query, C::Key, C::Sharded>) -> R,
377 if unlikely!(tcx.profiler().enabled()) {
378 tcx.profiler().query_cache_hit(index.into());
380 #[cfg(debug_assertions)]
382 state.cache_hits.fetch_add(1, Ordering::Relaxed);
390 fn try_execute_query<CTX, C>(
392 state: &QueryState<CTX::DepKind, CTX::Query, C>,
395 lookup: QueryLookup<'_, CTX::DepKind, CTX::Query, C::Key, C::Sharded>,
396 query: &QueryVtable<CTX, C::Key, C::Value>,
400 C::Key: crate::dep_graph::DepNodeParams<CTX>,
403 let job = match JobOwner::<'_, CTX::DepKind, CTX::Query, C>::try_start(
404 tcx, state, span, &key, lookup, query,
406 TryGetJob::NotYetStarted(job) => job,
407 TryGetJob::Cycle(result) => return result,
408 #[cfg(parallel_compiler)]
409 TryGetJob::JobCompleted((v, index)) => {
410 tcx.dep_graph().read_index(index);
415 // Fast path for when incr. comp. is off. `to_dep_node` is
416 // expensive for some `DepKind`s.
417 if !tcx.dep_graph().is_fully_enabled() {
418 let null_dep_node = DepNode::new_no_params(DepKind::NULL);
419 return force_query_with_job(tcx, key, job, null_dep_node, query).0;
423 let prof_timer = tcx.profiler().query_provider();
425 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
426 tcx.start_query(job.id, diagnostics, |tcx| {
427 tcx.dep_graph().with_anon_task(query.dep_kind, || query.compute(tcx, key))
431 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
433 tcx.dep_graph().read_index(dep_node_index);
435 if unlikely!(!diagnostics.is_empty()) {
436 tcx.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
439 return job.complete(result, dep_node_index);
442 let dep_node = query.to_dep_node(tcx, &key);
444 if !query.eval_always {
445 // The diagnostics for this query will be
446 // promoted to the current session during
447 // `try_mark_green()`, so we can ignore them here.
448 let loaded = tcx.start_query(job.id, None, |tcx| {
449 let marked = tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node);
450 marked.map(|(prev_dep_node_index, dep_node_index)| {
452 load_from_disk_and_cache_in_memory(
464 if let Some((result, dep_node_index)) = loaded {
465 return job.complete(result, dep_node_index);
469 let (result, dep_node_index) = force_query_with_job(tcx, key, job, dep_node, query);
470 tcx.dep_graph().read_index(dep_node_index);
474 fn load_from_disk_and_cache_in_memory<CTX, K, V: Debug>(
477 prev_dep_node_index: SerializedDepNodeIndex,
478 dep_node_index: DepNodeIndex,
479 dep_node: &DepNode<CTX::DepKind>,
480 query: &QueryVtable<CTX, K, V>,
485 // Note this function can be called concurrently from the same query
486 // We must ensure that this is handled correctly.
488 debug_assert!(tcx.dep_graph().is_green(dep_node));
490 // First we try to load the result from the on-disk cache.
491 let result = if query.cache_on_disk(tcx, &key, None) {
492 let prof_timer = tcx.profiler().incr_cache_loading();
493 let result = query.try_load_from_disk(tcx, prev_dep_node_index);
494 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
496 // We always expect to find a cached result for things that
497 // can be forced from `DepNode`.
499 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
500 "missing on-disk cache entry for {:?}",
505 // Some things are never cached on disk.
509 let result = if let Some(result) = result {
512 // We could not load a result from the on-disk cache, so
514 let prof_timer = tcx.profiler().query_provider();
516 // The dep-graph for this computation is already in-place.
517 let result = tcx.dep_graph().with_ignore(|| query.compute(tcx, key));
519 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
524 // If `-Zincremental-verify-ich` is specified, re-hash results from
525 // the cache and make sure that they have the expected fingerprint.
526 if unlikely!(tcx.incremental_verify_ich()) {
527 incremental_verify_ich(tcx, &result, dep_node, dep_node_index, query);
535 fn incremental_verify_ich<CTX, K, V: Debug>(
538 dep_node: &DepNode<CTX::DepKind>,
539 dep_node_index: DepNodeIndex,
540 query: &QueryVtable<CTX, K, V>,
545 Some(tcx.dep_graph().fingerprint_of(dep_node_index))
546 == tcx.dep_graph().prev_fingerprint_of(dep_node),
547 "fingerprint for green query instance not loaded from cache: {:?}",
551 debug!("BEGIN verify_ich({:?})", dep_node);
552 let mut hcx = tcx.create_stable_hashing_context();
554 let new_hash = query.hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
555 debug!("END verify_ich({:?})", dep_node);
557 let old_hash = tcx.dep_graph().fingerprint_of(dep_node_index);
559 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
562 fn force_query_with_job<C, CTX>(
565 job: JobOwner<'_, CTX::DepKind, CTX::Query, C>,
566 dep_node: DepNode<CTX::DepKind>,
567 query: &QueryVtable<CTX, C::Key, C::Value>,
568 ) -> (C::Stored, DepNodeIndex)
573 // If the following assertion triggers, it can have two reasons:
574 // 1. Something is wrong with DepNode creation, either here or
575 // in `DepGraph::try_mark_green()`.
576 // 2. Two distinct query keys get mapped to the same `DepNode`
577 // (see for example #48923).
579 !tcx.dep_graph().dep_node_exists(&dep_node),
580 "forcing query with already existing `DepNode`\n\
587 let prof_timer = tcx.profiler().query_provider();
589 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
590 tcx.start_query(job.id, diagnostics, |tcx| {
591 if query.eval_always {
592 tcx.dep_graph().with_eval_always_task(
600 tcx.dep_graph().with_task(dep_node, tcx, key, query.compute, query.hash_result)
605 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
607 if unlikely!(!diagnostics.is_empty()) && dep_node.kind != DepKind::NULL {
608 tcx.store_diagnostics(dep_node_index, diagnostics);
611 let result = job.complete(result, dep_node_index);
613 (result, dep_node_index)
617 fn get_query_impl<CTX, C>(
619 state: &QueryState<CTX::DepKind, CTX::Query, C>,
622 query: &QueryVtable<CTX, C::Key, C::Value>,
627 C::Key: crate::dep_graph::DepNodeParams<CTX>,
634 tcx.dep_graph().read_index(index);
637 |key, lookup| try_execute_query(tcx, state, span, key, lookup, query),
641 /// Ensure that either this query has all green inputs or been executed.
642 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
643 /// Returns true if the query should still run.
645 /// This function is particularly useful when executing passes for their
646 /// side-effects -- e.g., in order to report errors for erroneous programs.
648 /// Note: The optimization is only available during incr. comp.
650 fn ensure_must_run<CTX, K, V>(tcx: CTX, key: &K, query: &QueryVtable<CTX, K, V>) -> bool
652 K: crate::dep_graph::DepNodeParams<CTX>,
655 if query.eval_always {
659 // Ensuring an anonymous query makes no sense
660 assert!(!query.anon);
662 let dep_node = query.to_dep_node(tcx, key);
664 match tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node) {
666 // A None return from `try_mark_green_and_read` means that this is either
667 // a new dep node or that the dep node has already been marked red.
668 // Either way, we can't call `dep_graph.read()` as we don't have the
669 // DepNodeIndex. We must invoke the query itself. The performance cost
670 // this introduces should be negligible as we'll immediately hit the
671 // in-memory cache, or another query down the line will.
674 Some((_, dep_node_index)) => {
675 tcx.profiler().query_cache_hit(dep_node_index.into());
682 fn force_query_impl<CTX, C>(
684 state: &QueryState<CTX::DepKind, CTX::Query, C>,
687 dep_node: DepNode<CTX::DepKind>,
688 query: &QueryVtable<CTX, C::Key, C::Value>,
691 C::Key: crate::dep_graph::DepNodeParams<CTX>,
694 // We may be concurrently trying both execute and force a query.
695 // Ensure that only one of them runs the query.
702 // Cache hit, do nothing
705 let job = match JobOwner::<'_, CTX::DepKind, CTX::Query, C>::try_start(
706 tcx, state, span, &key, lookup, query,
708 TryGetJob::NotYetStarted(job) => job,
709 TryGetJob::Cycle(_) => return,
710 #[cfg(parallel_compiler)]
711 TryGetJob::JobCompleted(_) => return,
713 force_query_with_job(tcx, key, job, dep_node, query);
723 pub fn get_query<Q, CTX>(tcx: CTX, span: Span, key: Q::Key, mode: QueryMode) -> Option<Q::Stored>
725 Q: QueryDescription<CTX>,
726 Q::Key: crate::dep_graph::DepNodeParams<CTX>,
729 let query = &Q::VTABLE;
730 if let QueryMode::Ensure = mode {
731 if !ensure_must_run(tcx, &key, query) {
736 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
737 let value = get_query_impl(tcx, Q::query_state(tcx), span, key, query);
741 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, span: Span, dep_node: DepNode<CTX::DepKind>)
743 Q: QueryDescription<CTX>,
744 Q::Key: crate::dep_graph::DepNodeParams<CTX>,
747 force_query_impl(tcx, Q::query_state(tcx), key, span, dep_node, &Q::VTABLE)