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;
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 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> {
54 pub(super) fn get_lookup<'tcx>(
57 ) -> QueryLookup<'tcx, CTX, C::Key, C::Sharded> {
58 // We compute the key's hash once and then use it for both the
59 // shard lookup and the hashmap lookup. This relies on the fact
60 // that both of them use `FxHasher`.
61 let mut hasher = FxHasher::default();
62 key.hash(&mut hasher);
63 let key_hash = hasher.finish();
65 let shard = self.shards.get_shard_index_by_hash(key_hash);
66 let lock = self.shards.get_shard_by_index(shard).lock();
67 QueryLookup { key_hash, shard, lock }
71 /// Indicates the state of a query for a given key in a query map.
72 enum QueryResult<CTX: QueryContext> {
73 /// An already executing query. The query job can be used to await for its completion.
74 Started(QueryJob<CTX>),
76 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
81 impl<CTX: QueryContext, C: QueryCache> QueryState<CTX, C> {
82 pub fn iter_results<R>(
84 f: impl for<'a> FnOnce(
85 Box<dyn Iterator<Item = (&'a C::Key, &'a C::Value, DepNodeIndex)> + 'a>,
88 self.cache.iter(&self.shards, |shard| &mut shard.cache, f)
91 pub fn all_inactive(&self) -> bool {
92 let shards = self.shards.lock_shards();
93 shards.iter().all(|shard| shard.active.is_empty())
96 pub fn try_collect_active_jobs(
99 make_query: fn(C::Key) -> CTX::Query,
100 jobs: &mut FxHashMap<QueryJobId<CTX::DepKind>, QueryJobInfo<CTX>>,
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 {
113 QueryJobId { job: job.id, shard: u16::try_from(shard_id).unwrap(), kind };
114 let info = QueryInfo { span: job.span, query: make_query(k.clone()) };
115 Some((id, QueryJobInfo { info, job: job.clone() }))
126 impl<CTX: QueryContext, C: QueryCache> Default for QueryState<CTX, C> {
127 fn default() -> QueryState<CTX, C> {
130 shards: Default::default(),
131 #[cfg(debug_assertions)]
132 cache_hits: AtomicUsize::new(0),
137 /// Values used when checking a query cache which can be reused on a cache-miss to execute the query.
138 pub struct QueryLookup<'tcx, CTX: QueryContext, K, C> {
139 pub(super) key_hash: u64,
141 pub(super) lock: LockGuard<'tcx, QueryStateShard<CTX, K, C>>,
144 /// A type representing the responsibility to execute the job in the `job` field.
145 /// This will poison the relevant query if dropped.
146 struct JobOwner<'tcx, CTX: QueryContext, C>
149 C::Key: Eq + Hash + Clone + Debug,
152 state: &'tcx QueryState<CTX, C>,
154 id: QueryJobId<CTX::DepKind>,
157 impl<'tcx, CTX: QueryContext, C> JobOwner<'tcx, CTX, C>
160 C::Key: Eq + Hash + Clone + Debug,
163 /// Either gets a `JobOwner` corresponding the query, allowing us to
164 /// start executing the query, or returns with the result of the query.
165 /// This function assumes that `try_get_cached` is already called and returned `lookup`.
166 /// If the query is executing elsewhere, this will wait for it and return the result.
167 /// If the query panicked, this will silently panic.
169 /// This function is inlined because that results in a noticeable speed-up
170 /// for some compile-time benchmarks.
172 fn try_start<'a, 'b, Q>(
176 mut lookup: QueryLookup<'a, CTX, C::Key, C::Sharded>,
177 ) -> TryGetJob<'b, CTX, C>
179 Q: QueryDescription<CTX, Key = C::Key, Value = C::Value, Cache = 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, Q::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, Q::DEP_KIND);
215 let job = tcx.current_query_job();
216 let job = QueryJob::new(id, span, job);
218 entry.insert(QueryResult::Started(job));
221 JobOwner { state: Q::query_state(tcx), id: global_id, key: (*key).clone() };
222 return TryGetJob::NotYetStarted(owner);
225 mem::drop(lookup.lock);
227 // If we are single-threaded we know that we have cycle error,
228 // so we just return the error.
229 #[cfg(not(parallel_compiler))]
230 return TryGetJob::Cycle(cold_path(|| {
231 Q::handle_cycle_error(tcx, latch.find_cycle_in_stack(tcx, span))
234 // With parallel queries we might just have to wait on some other
236 #[cfg(parallel_compiler)]
238 let result = latch.wait_on(tcx, span);
240 if let Err(cycle) = result {
241 return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
244 let cached = try_get_cached(
248 |value, index| (value.clone(), index),
249 |_, _| panic!("value must be in cache after waiting"),
252 if let Some(prof_timer) = _query_blocked_prof_timer.take() {
253 prof_timer.finish_with_query_invocation_id(cached.1.into());
256 return TryGetJob::JobCompleted(cached);
260 /// Completes the query by updating the query cache with the `result`,
261 /// signals the waiter and forgets the JobOwner, so it won't poison the query
263 fn complete(self, tcx: CTX, result: &C::Value, dep_node_index: DepNodeIndex) {
264 // We can move out of `self` here because we `mem::forget` it below
265 let key = unsafe { ptr::read(&self.key) };
266 let state = self.state;
268 // Forget ourself so our destructor won't poison the query
272 let result = result.clone();
273 let mut lock = state.shards.get_shard_by_value(&key).lock();
274 let job = match lock.active.remove(&key).unwrap() {
275 QueryResult::Started(job) => job,
276 QueryResult::Poisoned => panic!(),
278 state.cache.complete(tcx, &mut lock.cache, key, result, dep_node_index);
282 job.signal_complete();
287 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
289 F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
291 let diagnostics = Lock::new(ThinVec::new());
292 let result = f(Some(&diagnostics));
293 (result, diagnostics.into_inner())
296 impl<'tcx, CTX: QueryContext, C: QueryCache> Drop for JobOwner<'tcx, CTX, C>
298 C::Key: Eq + Hash + Clone + Debug,
304 // Poison the query so jobs waiting on it panic.
305 let state = self.state;
306 let shard = state.shards.get_shard_by_value(&self.key);
308 let mut shard = shard.lock();
309 let job = match shard.active.remove(&self.key).unwrap() {
310 QueryResult::Started(job) => job,
311 QueryResult::Poisoned => panic!(),
313 shard.active.insert(self.key.clone(), QueryResult::Poisoned);
316 // Also signal the completion of the job, so waiters
317 // will continue execution.
318 job.signal_complete();
323 pub struct CycleError<Q> {
324 /// The query and related span that uses the cycle.
325 pub usage: Option<(Span, Q)>,
326 pub cycle: Vec<QueryInfo<Q>>,
329 /// The result of `try_start`.
330 enum TryGetJob<'tcx, CTX: QueryContext, C: QueryCache>
332 C::Key: Eq + Hash + Clone + Debug,
335 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
336 NotYetStarted(JobOwner<'tcx, CTX, C>),
338 /// The query was already completed.
339 /// Returns the result of the query and its dep-node index
340 /// if it succeeded or a cycle error if it failed.
341 #[cfg(parallel_compiler)]
342 JobCompleted((C::Value, DepNodeIndex)),
344 /// Trying to execute the query resulted in a cycle.
348 /// Checks if the query is already computed and in the cache.
349 /// It returns the shard index and a lock guard to the shard,
350 /// which will be used if the query is not in the cache and we need
353 fn try_get_cached<CTX, C, R, OnHit, OnMiss>(
355 state: &QueryState<CTX, C>,
357 // `on_hit` can be called while holding a lock to the query cache
364 OnHit: FnOnce(&C::Value, DepNodeIndex) -> R,
365 OnMiss: FnOnce(C::Key, QueryLookup<'_, CTX, C::Key, C::Sharded>) -> R,
371 if unlikely!(tcx.profiler().enabled()) {
372 tcx.profiler().query_cache_hit(index.into());
374 #[cfg(debug_assertions)]
376 state.cache_hits.fetch_add(1, Ordering::Relaxed);
385 fn try_execute_query<Q, CTX>(
389 lookup: QueryLookup<'_, CTX, Q::Key, <Q::Cache as QueryCache>::Sharded>,
392 Q: QueryDescription<CTX>,
395 let job = match JobOwner::try_start::<Q>(tcx, span, &key, lookup) {
396 TryGetJob::NotYetStarted(job) => job,
397 TryGetJob::Cycle(result) => return result,
398 #[cfg(parallel_compiler)]
399 TryGetJob::JobCompleted((v, index)) => {
400 tcx.dep_graph().read_index(index);
405 // Fast path for when incr. comp. is off. `to_dep_node` is
406 // expensive for some `DepKind`s.
407 if !tcx.dep_graph().is_fully_enabled() {
408 let null_dep_node = DepNode::new_no_params(DepKind::NULL);
409 return force_query_with_job::<Q, _>(tcx, key, job, null_dep_node).0;
413 let prof_timer = tcx.profiler().query_provider();
415 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
416 tcx.start_query(job.id, diagnostics, |tcx| {
417 tcx.dep_graph().with_anon_task(Q::DEP_KIND, || Q::compute(tcx, key))
421 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
423 tcx.dep_graph().read_index(dep_node_index);
425 if unlikely!(!diagnostics.is_empty()) {
426 tcx.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
429 job.complete(tcx, &result, dep_node_index);
434 let dep_node = Q::to_dep_node(tcx, &key);
437 // The diagnostics for this query will be
438 // promoted to the current session during
439 // `try_mark_green()`, so we can ignore them here.
440 let loaded = tcx.start_query(job.id, None, |tcx| {
441 let marked = tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node);
442 marked.map(|(prev_dep_node_index, dep_node_index)| {
444 load_from_disk_and_cache_in_memory::<Q, _>(
455 if let Some((result, dep_node_index)) = loaded {
456 job.complete(tcx, &result, dep_node_index);
461 let (result, dep_node_index) = force_query_with_job::<Q, _>(tcx, key, job, dep_node);
462 tcx.dep_graph().read_index(dep_node_index);
466 fn load_from_disk_and_cache_in_memory<Q, CTX>(
469 prev_dep_node_index: SerializedDepNodeIndex,
470 dep_node_index: DepNodeIndex,
471 dep_node: &DepNode<CTX::DepKind>,
475 Q: QueryDescription<CTX>,
477 // Note this function can be called concurrently from the same query
478 // We must ensure that this is handled correctly.
480 debug_assert!(tcx.dep_graph().is_green(dep_node));
482 // First we try to load the result from the on-disk cache.
483 let result = if Q::cache_on_disk(tcx, key.clone(), None) {
484 let prof_timer = tcx.profiler().incr_cache_loading();
485 let result = Q::try_load_from_disk(tcx, prev_dep_node_index);
486 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
488 // We always expect to find a cached result for things that
489 // can be forced from `DepNode`.
491 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
492 "missing on-disk cache entry for {:?}",
497 // Some things are never cached on disk.
501 let result = if let Some(result) = result {
504 // We could not load a result from the on-disk cache, so
506 let prof_timer = tcx.profiler().query_provider();
508 // The dep-graph for this computation is already in-place.
509 let result = tcx.dep_graph().with_ignore(|| Q::compute(tcx, key));
511 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
516 // If `-Zincremental-verify-ich` is specified, re-hash results from
517 // the cache and make sure that they have the expected fingerprint.
518 if unlikely!(tcx.incremental_verify_ich()) {
519 incremental_verify_ich::<Q, _>(tcx, &result, dep_node, dep_node_index);
527 fn incremental_verify_ich<Q, CTX>(
530 dep_node: &DepNode<CTX::DepKind>,
531 dep_node_index: DepNodeIndex,
534 Q: QueryDescription<CTX>,
537 Some(tcx.dep_graph().fingerprint_of(dep_node_index))
538 == tcx.dep_graph().prev_fingerprint_of(dep_node),
539 "fingerprint for green query instance not loaded from cache: {:?}",
543 debug!("BEGIN verify_ich({:?})", dep_node);
544 let mut hcx = tcx.create_stable_hashing_context();
546 let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
547 debug!("END verify_ich({:?})", dep_node);
549 let old_hash = tcx.dep_graph().fingerprint_of(dep_node_index);
551 assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
555 fn force_query_with_job<Q, CTX>(
558 job: JobOwner<'_, CTX, Q::Cache>,
559 dep_node: DepNode<CTX::DepKind>,
560 ) -> (Q::Value, DepNodeIndex)
562 Q: QueryDescription<CTX>,
565 // If the following assertion triggers, it can have two reasons:
566 // 1. Something is wrong with DepNode creation, either here or
567 // in `DepGraph::try_mark_green()`.
568 // 2. Two distinct query keys get mapped to the same `DepNode`
569 // (see for example #48923).
571 !tcx.dep_graph().dep_node_exists(&dep_node),
572 "forcing query with already existing `DepNode`\n\
579 let prof_timer = tcx.profiler().query_provider();
581 let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
582 tcx.start_query(job.id, diagnostics, |tcx| {
584 tcx.dep_graph().with_eval_always_task(
592 tcx.dep_graph().with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
597 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
599 if unlikely!(!diagnostics.is_empty()) {
600 if dep_node.kind != DepKind::NULL {
601 tcx.store_diagnostics(dep_node_index, diagnostics);
605 job.complete(tcx, &result, dep_node_index);
607 (result, dep_node_index)
611 pub fn get_query<Q, CTX>(tcx: CTX, span: Span, key: Q::Key) -> Q::Value
613 Q: QueryDescription<CTX>,
616 debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME, key, span);
623 tcx.dep_graph().read_index(index);
626 |key, lookup| try_execute_query::<Q, _>(tcx, span, key, lookup),
630 /// Ensure that either this query has all green inputs or been executed.
631 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
633 /// This function is particularly useful when executing passes for their
634 /// side-effects -- e.g., in order to report errors for erroneous programs.
636 /// Note: The optimization is only available during incr. comp.
637 pub fn ensure_query<Q, CTX>(tcx: CTX, key: Q::Key)
639 Q: QueryDescription<CTX>,
643 let _ = get_query::<Q, _>(tcx, DUMMY_SP, key);
647 // Ensuring an anonymous query makes no sense
650 let dep_node = Q::to_dep_node(tcx, &key);
652 match tcx.dep_graph().try_mark_green_and_read(tcx, &dep_node) {
654 // A None return from `try_mark_green_and_read` means that this is either
655 // a new dep node or that the dep node has already been marked red.
656 // Either way, we can't call `dep_graph.read()` as we don't have the
657 // DepNodeIndex. We must invoke the query itself. The performance cost
658 // this introduces should be negligible as we'll immediately hit the
659 // in-memory cache, or another query down the line will.
660 let _ = get_query::<Q, _>(tcx, DUMMY_SP, key);
662 Some((_, dep_node_index)) => {
663 tcx.profiler().query_cache_hit(dep_node_index.into());
668 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, span: Span, dep_node: DepNode<CTX::DepKind>)
670 Q: QueryDescription<CTX>,
673 // We may be concurrently trying both execute and force a query.
674 // Ensure that only one of them runs the query.
681 // Cache hit, do nothing
684 let job = match JobOwner::try_start::<Q>(tcx, span, &key, lookup) {
685 TryGetJob::NotYetStarted(job) => job,
686 TryGetJob::Cycle(_) => return,
687 #[cfg(parallel_compiler)]
688 TryGetJob::JobCompleted(_) => return,
690 force_query_with_job::<Q, _>(tcx, key, job, dep_node);