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;
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};
20 use rustc_span::source_map::DUMMY_SP;
22 use std::collections::hash_map::Entry;
23 use std::convert::TryFrom;
25 use std::hash::{Hash, Hasher};
27 use std::num::NonZeroU32;
29 #[cfg(debug_assertions)]
30 use std::sync::atomic::{AtomicUsize, Ordering};
32 pub(super) struct QueryStateShard<CTX: QueryContext, K, C> {
34 active: FxHashMap<K, QueryResult<CTX>>,
36 /// Used to generate unique ids for active jobs.
40 impl<CTX: QueryContext, K, C: Default> Default for QueryStateShard<CTX, K, C> {
41 fn default() -> QueryStateShard<CTX, K, C> {
42 QueryStateShard { cache: Default::default(), active: Default::default(), jobs: 0 }
46 pub struct QueryState<CTX: QueryContext, C: QueryCache> {
48 shards: Sharded<QueryStateShard<CTX, C::Key, C::Sharded>>,
49 #[cfg(debug_assertions)]
50 pub cache_hits: AtomicUsize,
53 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
55 pub(super) fn get_lookup<'tcx>(
58 ) -> QueryLookup<'tcx, CTX, C::Key, C::Sharded> {
59 // We compute the key's hash once and then use it for both the
60 // shard lookup and the hashmap lookup. This relies on the fact
61 // that both of them use `FxHasher`.
62 let mut hasher = FxHasher::default();
63 key.hash(&mut hasher);
64 let key_hash = hasher.finish();
66 let shard = self.shards.get_shard_index_by_hash(key_hash);
67 let lock = self.shards.get_shard_by_index(shard).lock();
68 QueryLookup { key_hash, shard, lock }
72 /// Indicates the state of a query for a given key in a query map.
73 enum QueryResult<CTX: QueryContext> {
74 /// An already executing query. The query job can be used to await for its completion.
75 Started(QueryJob<CTX>),
77 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
82 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
84 pub fn iter_results<R>(
86 f: impl for<'a> FnOnce(
87 Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
90 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) -> CTX::Query,
103 jobs: &mut FxHashMap<QueryJobId<CTX::DepKind>, QueryJobInfo<CTX>>,
108 // We use try_lock_shards here since we are called from the
109 // deadlock handler, and this shouldn't be locked.
110 let shards = self.shards.try_lock_shards()?;
111 let shards = shards.iter().enumerate();
112 jobs.extend(shards.flat_map(|(shard_id, shard)| {
113 shard.active.iter().filter_map(move |(k, v)| {
114 if let QueryResult::Started(ref job) = *v {
116 QueryJobId { job: job.id, shard: u16::try_from(shard_id).unwrap(), kind };
117 let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
118 Some((id, QueryJobInfo { info, job: job.clone() }))
129 impl<CTX: QueryContext, C: QueryCache> Default for QueryState<CTX, C> {
130 fn default() -> QueryState<CTX, C> {
133 shards: Default::default(),
134 #[cfg(debug_assertions)]
135 cache_hits: AtomicUsize::new(0),
140 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
141 pub struct QueryLookup<'tcx, CTX: QueryContext, K, C> {
142 pub(super) key_hash: u64,
144 pub(super) lock: LockGuard<'tcx, QueryStateShard<CTX, K, C>>,
147 /// A type representing the responsibility to execute the job in the `job` field.
148 /// This will poison the relevant query if dropped.
149 struct JobOwner<'tcx, CTX: QueryContext, C>
152 C::Key: Eq + Hash + Clone + Debug,
154 state: &'tcx QueryState<CTX, C>,
156 id: QueryJobId<CTX::DepKind>,
159 impl<'tcx, CTX: QueryContext, C> JobOwner<'tcx, CTX, C>
162 C::Key: Eq + Hash + Clone + Debug,
164 /// Either gets a `JobOwner` corresponding the query, allowing us to
165 /// start executing the query, or returns with the result of the query.
166 /// This function assumes that `try_get_cached` is already called and returned `lookup`.
167 /// If the query is executing elsewhere, this will wait for it and return the result.
168 /// If the query panicked, this will silently panic.
170 /// This function is inlined because that results in a noticeable speed-up
171 /// for some compile-time benchmarks.
173 fn try_start<'a, 'b>(
175 state: &'b QueryState<CTX, C>,
178 mut lookup: QueryLookup<'a, CTX, C::Key, C::Sharded>,
179 query: &QueryVtable<CTX, C::Key, C::Value>,
180 ) -> TryGetJob<'b, CTX, C>
184 let lock = &mut *lookup.lock;
186 let (latch, mut _query_blocked_prof_timer) = match lock.active.entry((*key).clone()) {
187 Entry::Occupied(mut entry) => {
188 match entry.get_mut() {
189 QueryResult::Started(job) => {
190 // For parallel queries, we'll block and wait until the query running
191 // in another thread has completed. Record how long we wait in the
193 let _query_blocked_prof_timer = if cfg!(parallel_compiler) {
194 Some(tcx.profiler().query_blocked())
199 // Create the id of the job we're waiting for
200 let id = QueryJobId::new(job.id, lookup.shard, query.dep_kind);
202 (job.latch(id), _query_blocked_prof_timer)
204 QueryResult::Poisoned => FatalError.raise(),
207 Entry::Vacant(entry) => {
208 // No job entry for this query. Return a new one to be started later.
210 // Generate an id unique within this shard.
211 let id = lock.jobs.checked_add(1).unwrap();
213 let id = QueryShardJobId(NonZeroU32::new(id).unwrap());
215 let global_id = QueryJobId::new(id, lookup.shard, query.dep_kind);
217 let job = tcx.current_query_job();
218 let job = QueryJob::new(id, span, job);
220 entry.insert(QueryResult::Started(job));
222 let owner = JobOwner { state, id: global_id, key: (*key).clone() };
223 return TryGetJob::NotYetStarted(owner);
226 mem::drop(lookup.lock);
228 // If we are single-threaded we know that we have cycle error,
229 // so we just return the error.
230 #[cfg(not(parallel_compiler))]
231 return TryGetJob::Cycle(cold_path(|| {
232 let value = query.handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span));
233 state.cache.store_nocache(value)
236 // With parallel queries we might just have to wait on some other
238 #[cfg(parallel_compiler)]
240 let result = latch.wait_on(tcx, span);
242 if let Err(cycle) = result {
243 let value = query.handle_cycle_error(tcx, cycle);
244 let value = state.cache.store_nocache(value);
245 return TryGetJob::Cycle(value);
248 let cached = try_get_cached(
252 |value, index| (value.clone(), index),
253 |_, _| panic!("value must be in cache after waiting"),
256 if let Some(prof_timer) = _query_blocked_prof_timer.take() {
257 prof_timer.finish_with_query_invocation_id(cached.1.into());
260 return TryGetJob::JobCompleted(cached);
264 /// Completes the query by updating the query cache with the `result`,
265 /// signals the waiter and forgets the JobOwner, so it won't poison the query
267 fn complete(self, tcx: CTX, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored {
268 // We can move out of `self` here because we `mem::forget` it below
269 let key = unsafe { ptr::read(&self.key) };
270 let state = self.state;
272 // Forget ourself so our destructor won't poison the query
275 let (job, result) = {
276 let mut lock = state.shards.get_shard_by_value(&key).lock();
277 let job = match lock.active.remove(&key).unwrap() {
278 QueryResult::Started(job) => job,
279 QueryResult::Poisoned => panic!(),
281 let result = state.cache.complete(tcx, &mut lock.cache, key, result, dep_node_index);
285 job.signal_complete();
291 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
293 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
295 let diagnostics = Lock::new(ThinVec::new());
296 let result = f(Some(&diagnostics));
297 (result, diagnostics.into_inner())
300 impl<'tcx, CTX: QueryContext, C: QueryCache> Drop for JobOwner<'tcx, CTX, C>
302 C::Key: Eq + Hash + Clone + Debug,
307 // Poison the query so jobs waiting on it panic.
308 let state = self.state;
309 let shard = state.shards.get_shard_by_value(&self.key);
311 let mut shard = shard.lock();
312 let job = match shard.active.remove(&self.key).unwrap() {
313 QueryResult::Started(job) => job,
314 QueryResult::Poisoned => panic!(),
316 shard.active.insert(self.key.clone(), QueryResult::Poisoned);
319 // Also signal the completion of the job, so waiters
320 // will continue execution.
321 job.signal_complete();
326 pub struct CycleError<Q> {
327 /// The query and related span that uses the cycle.
328 pub usage: Option<(Span, Q)>,
329 pub cycle: Vec<QueryInfo<Q>>,
332 /// The result of `try_start`.
333 enum TryGetJob<'tcx, CTX: QueryContext, C: QueryCache>
335 C::Key: Eq + Hash + Clone + Debug,
337 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
338 NotYetStarted(JobOwner<'tcx, CTX, C>),
340 /// The query was already completed.
341 /// Returns the result of the query and its dep-node index
342 /// if it succeeded or a cycle error if it failed.
343 #[cfg(parallel_compiler)]
344 JobCompleted((C::Stored, DepNodeIndex)),
346 /// Trying to execute the query resulted in a cycle.
350 /// Checks if the query is already computed and in the cache.
351 /// It returns the shard index and a lock guard to the shard,
352 /// which will be used if the query is not in the cache and we need
355 fn try_get_cached<CTX, C, R, OnHit, OnMiss>(
357 state: &QueryState<CTX, C>,
359 // `on_hit` can be called while holding a lock to the query cache
366 OnHit: FnOnce(&C::Stored, DepNodeIndex) -> R,
367 OnMiss: FnOnce(C::Key, QueryLookup<'_, CTX, C::Key, C::Sharded>) -> R,
373 if unlikely!(tcx.profiler().enabled()) {
374 tcx.profiler().query_cache_hit(index.into());
376 #[cfg(debug_assertions)]
378 state.cache_hits.fetch_add(1, Ordering::Relaxed);
387 fn try_execute_query<CTX, C>(
389 state: &QueryState<CTX, C>,
392 lookup: QueryLookup<'_, CTX, C::Key, C::Sharded>,
393 query: &QueryVtable<CTX, C::Key, C::Value>,
397 C::Key: Eq + Clone + Debug + crate::dep_graph::DepNodeParams<CTX>,
401 let job = match JobOwner::try_start(tcx, state, span, &key, lookup, query) {
402 TryGetJob::NotYetStarted(job) => job,
403 TryGetJob::Cycle(result) => return result,
404 #[cfg(parallel_compiler)]
405 TryGetJob::JobCompleted((v, index)) => {
406 tcx.dep_graph().read_index(index);
411 // Fast path for when incr. comp. is off. `to_dep_node` is
412 // expensive for some `DepKind`s.
413 if !tcx.dep_graph().is_fully_enabled() {
414 let null_dep_node = DepNode::new_no_params(DepKind::NULL);
415 return force_query_with_job(tcx, key, job, null_dep_node, query).0;
419 let prof_timer = tcx.profiler().query_provider();
421 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
422 tcx.start_query(job.id, diagnostics, |tcx| {
423 tcx.dep_graph().with_anon_task(query.dep_kind, || query.compute(tcx, key))
427 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
429 tcx.dep_graph().read_index(dep_node_index);
431 if unlikely!(!diagnostics.is_empty()) {
432 tcx.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
435 return job.complete(tcx, result, dep_node_index);
438 let dep_node = query.to_dep_node(tcx, &key);
440 if !query.eval_always {
441 // The diagnostics for this query will be
442 // promoted to the current session during
443 // `try_mark_green()`, so we can ignore them here.
444 let loaded = tcx.start_query(job.id, None, |tcx| {
445 let marked = tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node);
446 marked.map(|(prev_dep_node_index, dep_node_index)| {
448 load_from_disk_and_cache_in_memory(
460 if let Some((result, dep_node_index)) = loaded {
461 return job.complete(tcx, result, dep_node_index);
465 let (result, dep_node_index) = force_query_with_job(tcx, key, job, dep_node, query);
466 tcx.dep_graph().read_index(dep_node_index);
470 fn load_from_disk_and_cache_in_memory<CTX, K, V>(
473 prev_dep_node_index: SerializedDepNodeIndex,
474 dep_node_index: DepNodeIndex,
475 dep_node: &DepNode<CTX::DepKind>,
476 query: &QueryVtable<CTX, K, V>,
481 // Note this function can be called concurrently from the same query
482 // We must ensure that this is handled correctly.
484 debug_assert!(tcx.dep_graph().is_green(dep_node));
486 // First we try to load the result from the on-disk cache.
487 let result = if query.cache_on_disk(tcx, &key, None) {
488 let prof_timer = tcx.profiler().incr_cache_loading();
489 let result = query.try_load_from_disk(tcx, prev_dep_node_index);
490 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
492 // We always expect to find a cached result for things that
493 // can be forced from `DepNode`.
495 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
496 "missing on-disk cache entry for {:?}",
501 // Some things are never cached on disk.
505 let result = if let Some(result) = result {
508 // We could not load a result from the on-disk cache, so
510 let prof_timer = tcx.profiler().query_provider();
512 // The dep-graph for this computation is already in-place.
513 let result = tcx.dep_graph().with_ignore(|| query.compute(tcx, key));
515 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
520 // If `-Zincremental-verify-ich` is specified, re-hash results from
521 // the cache and make sure that they have the expected fingerprint.
522 if unlikely!(tcx.incremental_verify_ich()) {
523 incremental_verify_ich(tcx, &result, dep_node, dep_node_index, query);
531 fn incremental_verify_ich<CTX, K, V>(
534 dep_node: &DepNode<CTX::DepKind>,
535 dep_node_index: DepNodeIndex,
536 query: &QueryVtable<CTX, K, V>,
541 Some(tcx.dep_graph().fingerprint_of(dep_node_index))
542 == tcx.dep_graph().prev_fingerprint_of(dep_node),
543 "fingerprint for green query instance not loaded from cache: {:?}",
547 debug!("BEGIN verify_ich({:?})", dep_node);
548 let mut hcx = tcx.create_stable_hashing_context();
550 let new_hash = query.hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
551 debug!("END verify_ich({:?})", dep_node);
553 let old_hash = tcx.dep_graph().fingerprint_of(dep_node_index);
555 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
559 fn force_query_with_job<C, CTX>(
562 job: JobOwner<'_, CTX, C>,
563 dep_node: DepNode<CTX::DepKind>,
564 query: &QueryVtable<CTX, C::Key, C::Value>,
565 ) -> (C::Stored, DepNodeIndex)
568 C::Key: Eq + Clone + Debug,
572 // If the following assertion triggers, it can have two reasons:
573 // 1. Something is wrong with DepNode creation, either here or
574 // in `DepGraph::try_mark_green()`.
575 // 2. Two distinct query keys get mapped to the same `DepNode`
576 // (see for example #48923).
578 !tcx.dep_graph().dep_node_exists(&dep_node),
579 "forcing query with already existing `DepNode`\n\
586 let prof_timer = tcx.profiler().query_provider();
588 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
589 tcx.start_query(job.id, diagnostics, |tcx| {
590 if query.eval_always {
591 tcx.dep_graph().with_eval_always_task(
599 tcx.dep_graph().with_task(dep_node, tcx, key, query.compute, query.hash_result)
604 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
606 if unlikely!(!diagnostics.is_empty()) {
607 if dep_node.kind != DepKind::NULL {
608 tcx.store_diagnostics(dep_node_index, diagnostics);
612 let result = job.complete(tcx, result, dep_node_index);
614 (result, dep_node_index)
618 fn get_query_impl<CTX, C>(
620 state: &QueryState<CTX, C>,
623 query: &QueryVtable<CTX, C::Key, C::Value>,
628 C::Key: Eq + Clone + crate::dep_graph::DepNodeParams<CTX>,
636 tcx.dep_graph().read_index(index);
639 |key, lookup| try_execute_query(tcx, state, span, key, lookup, query),
643 /// Ensure that either this query has all green inputs or been executed.
644 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
646 /// This function is particularly useful when executing passes for their
647 /// side-effects -- e.g., in order to report errors for erroneous programs.
649 /// Note: The optimization is only available during incr. comp.
651 fn ensure_query_impl<CTX, C>(
653 state: &QueryState<CTX, C>,
655 query: &QueryVtable<CTX, C::Key, C::Value>,
658 C::Key: Eq + Clone + crate::dep_graph::DepNodeParams<CTX>,
661 if query.eval_always {
662 let _ = get_query_impl(tcx, state, DUMMY_SP, key, query);
666 // Ensuring an anonymous query makes no sense
667 assert!(!query.anon);
669 let dep_node = query.to_dep_node(tcx, &key);
671 match tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node) {
673 // A None return from `try_mark_green_and_read` means that this is either
674 // a new dep node or that the dep node has already been marked red.
675 // Either way, we can't call `dep_graph.read()` as we don't have the
676 // DepNodeIndex. We must invoke the query itself. The performance cost
677 // this introduces should be negligible as we'll immediately hit the
678 // in-memory cache, or another query down the line will.
679 let _ = get_query_impl(tcx, state, DUMMY_SP, key, query);
681 Some((_, dep_node_index)) => {
682 tcx.profiler().query_cache_hit(dep_node_index.into());
688 fn force_query_impl<CTX, C>(
690 state: &QueryState<CTX, C>,
693 dep_node: DepNode<CTX::DepKind>,
694 query: &QueryVtable<CTX, C::Key, C::Value>,
697 C::Key: Eq + Clone + crate::dep_graph::DepNodeParams<CTX>,
700 // We may be concurrently trying both execute and force a query.
701 // Ensure that only one of them runs the query.
708 // Cache hit, do nothing
711 let job = match JobOwner::try_start(tcx, state, span, &key, lookup, query) {
712 TryGetJob::NotYetStarted(job) => job,
713 TryGetJob::Cycle(_) => return,
714 #[cfg(parallel_compiler)]
715 TryGetJob::JobCompleted(_) => return,
717 force_query_with_job(tcx, key, job, dep_node, query);
723 pub fn get_query<Q, CTX>(tcx: CTX, span: Span, key: Q::Key) -> Q::Stored
725 Q: QueryDescription<CTX>,
726 Q::Key: crate::dep_graph::DepNodeParams<CTX>,
729 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
731 get_query_impl(tcx, Q::query_state(tcx), span, key, &Q::VTABLE)
735 pub fn ensure_query<Q, CTX>(tcx: CTX, key: Q::Key)
737 Q: QueryDescription<CTX>,
738 Q::Key: crate::dep_graph::DepNodeParams<CTX>,
741 ensure_query_impl(tcx, Q::query_state(tcx), key, &Q::VTABLE)
745 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, span: Span, dep_node: DepNode<CTX::DepKind>)
747 Q: QueryDescription<CTX>,
748 Q::Key: crate::dep_graph::DepNodeParams<CTX>,
751 force_query_impl(tcx, Q::query_state(tcx), key, span, dep_node, &Q::VTABLE)