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::{DepContext, DepNode, DepNodeIndex, DepNodeParams};
6 use crate::query::caches::QueryCache;
7 use crate::query::config::{QueryDescription, QueryVTable};
8 use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo};
9 use crate::query::{QueryContext, QueryMap, QuerySideEffects, QueryStackFrame};
10 use crate::values::Value;
11 use crate::HandleCycleError;
12 use rustc_data_structures::fingerprint::Fingerprint;
13 use rustc_data_structures::fx::FxHashMap;
14 #[cfg(parallel_compiler)]
15 use rustc_data_structures::profiling::TimingGuard;
16 #[cfg(parallel_compiler)]
17 use rustc_data_structures::sharded::Sharded;
18 use rustc_data_structures::sync::Lock;
19 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, FatalError};
20 use rustc_session::Session;
21 use rustc_span::{Span, DUMMY_SP};
23 use std::collections::hash_map::Entry;
28 use thin_vec::ThinVec;
30 pub struct QueryState<K> {
31 #[cfg(parallel_compiler)]
32 active: Sharded<FxHashMap<K, QueryResult>>,
33 #[cfg(not(parallel_compiler))]
34 active: Lock<FxHashMap<K, QueryResult>>,
37 /// Indicates the state of a query for a given key in a query map.
39 /// An already executing query. The query job can be used to await for its completion.
42 /// The query panicked. Queries trying to wait on this will raise a fatal error which will
49 K: Eq + Hash + Clone + Debug,
51 pub fn all_inactive(&self) -> bool {
52 #[cfg(parallel_compiler)]
54 let shards = self.active.lock_shards();
55 shards.iter().all(|shard| shard.is_empty())
57 #[cfg(not(parallel_compiler))]
59 self.active.lock().is_empty()
63 pub fn try_collect_active_jobs<CTX: Copy>(
66 make_query: fn(CTX, K) -> QueryStackFrame,
69 #[cfg(parallel_compiler)]
71 // We use try_lock_shards here since we are called from the
72 // deadlock handler, and this shouldn't be locked.
73 let shards = self.active.try_lock_shards()?;
74 for shard in shards.iter() {
75 for (k, v) in shard.iter() {
76 if let QueryResult::Started(ref job) = *v {
77 let query = make_query(tcx, k.clone());
78 jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
83 #[cfg(not(parallel_compiler))]
85 // We use try_lock here since we are called from the
86 // deadlock handler, and this shouldn't be locked.
87 // (FIXME: Is this relevant for non-parallel compilers? It doesn't
89 for (k, v) in self.active.try_lock()?.iter() {
90 if let QueryResult::Started(ref job) = *v {
91 let query = make_query(tcx, k.clone());
92 jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
101 impl<K> Default for QueryState<K> {
102 fn default() -> QueryState<K> {
103 QueryState { active: Default::default() }
107 /// A type representing the responsibility to execute the job in the `job` field.
108 /// This will poison the relevant query if dropped.
109 struct JobOwner<'tcx, K>
111 K: Eq + Hash + Clone,
113 state: &'tcx QueryState<K>,
120 fn mk_cycle<CTX, V, R>(
123 handler: HandleCycleError,
124 cache: &dyn crate::query::QueryStorage<Value = V, Stored = R>,
128 V: std::fmt::Debug + Value<CTX::DepContext>,
131 let error = report_cycle(tcx.dep_context().sess(), error);
132 let value = handle_cycle_error(*tcx.dep_context(), error, handler);
133 cache.store_nocache(value)
136 fn handle_cycle_error<CTX, V>(
138 mut error: DiagnosticBuilder<'_, ErrorGuaranteed>,
139 handler: HandleCycleError,
145 use HandleCycleError::*;
149 Value::from_cycle_error(tcx)
153 tcx.sess().abort_if_errors();
157 error.delay_as_bug();
158 Value::from_cycle_error(tcx)
163 impl<'tcx, K> JobOwner<'tcx, K>
165 K: Eq + Hash + Clone,
167 /// Either gets a `JobOwner` corresponding the query, allowing us to
168 /// start executing the query, or returns with the result of the query.
169 /// This function assumes that `try_get_cached` is already called and returned `lookup`.
170 /// If the query is executing elsewhere, this will wait for it and return the result.
171 /// If the query panicked, this will silently panic.
173 /// This function is inlined because that results in a noticeable speed-up
174 /// for some compile-time benchmarks.
176 fn try_start<'b, CTX>(
178 state: &'b QueryState<K>,
181 ) -> TryGetJob<'b, K>
185 #[cfg(parallel_compiler)]
186 let mut state_lock = state.active.get_shard_by_value(&key).lock();
187 #[cfg(not(parallel_compiler))]
188 let mut state_lock = state.active.lock();
189 let lock = &mut *state_lock;
191 match lock.entry(key) {
192 Entry::Vacant(entry) => {
193 let id = tcx.next_job_id();
194 let job = tcx.current_query_job();
195 let job = QueryJob::new(id, span, job);
197 let key = entry.key().clone();
198 entry.insert(QueryResult::Started(job));
200 let owner = JobOwner { state, id, key };
201 return TryGetJob::NotYetStarted(owner);
203 Entry::Occupied(mut entry) => {
204 match entry.get_mut() {
205 #[cfg(not(parallel_compiler))]
206 QueryResult::Started(job) => {
210 // If we are single-threaded we know that we have cycle error,
211 // so we just return the error.
212 return TryGetJob::Cycle(id.find_cycle_in_stack(
213 tcx.try_collect_active_jobs().unwrap(),
214 &tcx.current_query_job(),
218 #[cfg(parallel_compiler)]
219 QueryResult::Started(job) => {
220 // For parallel queries, we'll block and wait until the query running
221 // in another thread has completed. Record how long we wait in the
223 let query_blocked_prof_timer = tcx.dep_context().profiler().query_blocked();
226 let latch = job.latch();
230 // With parallel queries we might just have to wait on some other
232 let result = latch.wait_on(tcx.current_query_job(), span);
235 Ok(()) => TryGetJob::JobCompleted(query_blocked_prof_timer),
236 Err(cycle) => TryGetJob::Cycle(cycle),
239 QueryResult::Poisoned => FatalError.raise(),
245 /// Completes the query by updating the query cache with the `result`,
246 /// signals the waiter and forgets the JobOwner, so it won't poison the query
247 fn complete<C>(self, cache: &C, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored
249 C: QueryCache<Key = K>,
251 // We can move out of `self` here because we `mem::forget` it below
252 let key = unsafe { ptr::read(&self.key) };
253 let state = self.state;
255 // Forget ourself so our destructor won't poison the query
258 let (job, result) = {
260 #[cfg(parallel_compiler)]
261 let mut lock = state.active.get_shard_by_value(&key).lock();
262 #[cfg(not(parallel_compiler))]
263 let mut lock = state.active.lock();
264 match lock.remove(&key).unwrap() {
265 QueryResult::Started(job) => job,
266 QueryResult::Poisoned => panic!(),
269 let result = cache.complete(key, result, dep_node_index);
273 job.signal_complete();
278 impl<'tcx, K> Drop for JobOwner<'tcx, K>
280 K: Eq + Hash + Clone,
285 // Poison the query so jobs waiting on it panic.
286 let state = self.state;
288 #[cfg(parallel_compiler)]
289 let mut shard = state.active.get_shard_by_value(&self.key).lock();
290 #[cfg(not(parallel_compiler))]
291 let mut shard = state.active.lock();
292 let job = match shard.remove(&self.key).unwrap() {
293 QueryResult::Started(job) => job,
294 QueryResult::Poisoned => panic!(),
296 shard.insert(self.key.clone(), QueryResult::Poisoned);
299 // Also signal the completion of the job, so waiters
300 // will continue execution.
301 job.signal_complete();
306 pub(crate) struct CycleError {
307 /// The query and related span that uses the cycle.
308 pub usage: Option<(Span, QueryStackFrame)>,
309 pub cycle: Vec<QueryInfo>,
312 /// The result of `try_start`.
313 enum TryGetJob<'tcx, K>
315 K: Eq + Hash + Clone,
317 /// The query is not yet started. Contains a guard to the cache eventually used to start it.
318 NotYetStarted(JobOwner<'tcx, K>),
320 /// The query was already completed.
321 /// Returns the result of the query and its dep-node index
322 /// if it succeeded or a cycle error if it failed.
323 #[cfg(parallel_compiler)]
324 JobCompleted(TimingGuard<'tcx>),
326 /// Trying to execute the query resulted in a cycle.
330 /// Checks if the query is already computed and in the cache.
331 /// It returns the shard index and a lock guard to the shard,
332 /// which will be used if the query is not in the cache and we need
335 pub fn try_get_cached<'a, CTX, C, R, OnHit>(
339 // `on_hit` can be called while holding a lock to the query cache
345 OnHit: FnOnce(&C::Stored) -> R,
347 cache.lookup(&key, |value, index| {
348 if std::intrinsics::unlikely(tcx.profiler().enabled()) {
349 tcx.profiler().query_cache_hit(index.into());
351 tcx.dep_graph().read_index(index);
356 fn try_execute_query<CTX, C>(
358 state: &QueryState<C::Key>,
362 dep_node: Option<DepNode<CTX::DepKind>>,
363 query: &QueryVTable<CTX, C::Key, C::Value>,
364 ) -> (C::Stored, Option<DepNodeIndex>)
367 C::Key: Clone + DepNodeParams<CTX::DepContext>,
368 C::Value: Value<CTX::DepContext>,
371 match JobOwner::<'_, C::Key>::try_start(&tcx, state, span, key.clone()) {
372 TryGetJob::NotYetStarted(job) => {
373 let (result, dep_node_index) = execute_job(tcx, key, dep_node, query, job.id);
374 let result = job.complete(cache, result, dep_node_index);
375 (result, Some(dep_node_index))
377 TryGetJob::Cycle(error) => {
378 let result = mk_cycle(tcx, error, query.handle_cycle_error, cache);
381 #[cfg(parallel_compiler)]
382 TryGetJob::JobCompleted(query_blocked_prof_timer) => {
383 let (v, index) = cache
384 .lookup(&key, |value, index| (value.clone(), index))
385 .unwrap_or_else(|_| panic!("value must be in cache after waiting"));
387 if std::intrinsics::unlikely(tcx.dep_context().profiler().enabled()) {
388 tcx.dep_context().profiler().query_cache_hit(index.into());
390 query_blocked_prof_timer.finish_with_query_invocation_id(index.into());
397 fn execute_job<CTX, K, V>(
400 mut dep_node_opt: Option<DepNode<CTX::DepKind>>,
401 query: &QueryVTable<CTX, K, V>,
403 ) -> (V, DepNodeIndex)
405 K: Clone + DepNodeParams<CTX::DepContext>,
409 let dep_graph = tcx.dep_context().dep_graph();
411 // Fast path for when incr. comp. is off.
412 if !dep_graph.is_fully_enabled() {
413 let prof_timer = tcx.dep_context().profiler().query_provider();
414 let result = tcx.start_query(job_id, query.depth_limit, None, || {
415 query.compute(*tcx.dep_context(), key)
417 let dep_node_index = dep_graph.next_virtual_depnode_index();
418 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
419 return (result, dep_node_index);
422 if !query.anon && !query.eval_always {
423 // `to_dep_node` is expensive for some `DepKind`s.
425 dep_node_opt.get_or_insert_with(|| query.to_dep_node(*tcx.dep_context(), &key));
427 // The diagnostics for this query will be promoted to the current session during
428 // `try_mark_green()`, so we can ignore them here.
429 if let Some(ret) = tcx.start_query(job_id, false, None, || {
430 try_load_from_disk_and_cache_in_memory(tcx, &key, &dep_node, query)
436 let prof_timer = tcx.dep_context().profiler().query_provider();
437 let diagnostics = Lock::new(ThinVec::new());
439 let (result, dep_node_index) =
440 tcx.start_query(job_id, query.depth_limit, Some(&diagnostics), || {
442 return dep_graph.with_anon_task(*tcx.dep_context(), query.dep_kind, || {
443 query.compute(*tcx.dep_context(), key)
447 // `to_dep_node` is expensive for some `DepKind`s.
449 dep_node_opt.unwrap_or_else(|| query.to_dep_node(*tcx.dep_context(), &key));
451 dep_graph.with_task(dep_node, *tcx.dep_context(), key, query.compute, query.hash_result)
454 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
456 let diagnostics = diagnostics.into_inner();
457 let side_effects = QuerySideEffects { diagnostics };
459 if std::intrinsics::unlikely(!side_effects.is_empty()) {
461 tcx.store_side_effects_for_anon_node(dep_node_index, side_effects);
463 tcx.store_side_effects(dep_node_index, side_effects);
467 (result, dep_node_index)
470 fn try_load_from_disk_and_cache_in_memory<CTX, K, V>(
473 dep_node: &DepNode<CTX::DepKind>,
474 query: &QueryVTable<CTX, K, V>,
475 ) -> Option<(V, DepNodeIndex)>
481 // Note this function can be called concurrently from the same query
482 // We must ensure that this is handled correctly.
484 let dep_graph = tcx.dep_context().dep_graph();
485 let (prev_dep_node_index, dep_node_index) = dep_graph.try_mark_green(tcx, &dep_node)?;
487 debug_assert!(dep_graph.is_green(dep_node));
489 // First we try to load the result from the on-disk cache.
490 // Some things are never cached on disk.
491 if let Some(try_load_from_disk) = query.try_load_from_disk {
492 let prof_timer = tcx.dep_context().profiler().incr_cache_loading();
494 // The call to `with_query_deserialization` enforces that no new `DepNodes`
495 // are created during deserialization. See the docs of that method for more
498 dep_graph.with_query_deserialization(|| try_load_from_disk(tcx, prev_dep_node_index));
500 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
502 if let Some(result) = result {
503 if std::intrinsics::unlikely(
504 tcx.dep_context().sess().opts.unstable_opts.query_dep_graph,
506 dep_graph.mark_debug_loaded_from_disk(*dep_node)
509 let prev_fingerprint = tcx
512 .prev_fingerprint_of(dep_node)
513 .unwrap_or(Fingerprint::ZERO);
514 // If `-Zincremental-verify-ich` is specified, re-hash results from
515 // the cache and make sure that they have the expected fingerprint.
517 // If not, we still seek to verify a subset of fingerprints loaded
518 // from disk. Re-hashing results is fairly expensive, so we can't
519 // currently afford to verify every hash. This subset should still
520 // give us some coverage of potential bugs though.
521 let try_verify = prev_fingerprint.as_value().1 % 32 == 0;
522 if std::intrinsics::unlikely(
523 try_verify || tcx.dep_context().sess().opts.unstable_opts.incremental_verify_ich,
525 incremental_verify_ich(*tcx.dep_context(), &result, dep_node, query);
528 return Some((result, dep_node_index));
531 // We always expect to find a cached result for things that
532 // can be forced from `DepNode`.
534 !tcx.dep_context().fingerprint_style(dep_node.kind).reconstructible(),
535 "missing on-disk cache entry for {:?}",
540 // We could not load a result from the on-disk cache, so
542 let prof_timer = tcx.dep_context().profiler().query_provider();
544 // The dep-graph for this computation is already in-place.
545 let result = dep_graph.with_ignore(|| query.compute(*tcx.dep_context(), key.clone()));
547 prof_timer.finish_with_query_invocation_id(dep_node_index.into());
549 // Verify that re-running the query produced a result with the expected hash
550 // This catches bugs in query implementations, turning them into ICEs.
551 // For example, a query might sort its result by `DefId` - since `DefId`s are
552 // not stable across compilation sessions, the result could get up getting sorted
553 // in a different order when the query is re-run, even though all of the inputs
554 // (e.g. `DefPathHash` values) were green.
556 // See issue #82920 for an example of a miscompilation that would get turned into
557 // an ICE by this check
558 incremental_verify_ich(*tcx.dep_context(), &result, dep_node, query);
560 Some((result, dep_node_index))
563 fn incremental_verify_ich<CTX, K, V: Debug>(
564 tcx: CTX::DepContext,
566 dep_node: &DepNode<CTX::DepKind>,
567 query: &QueryVTable<CTX, K, V>,
572 tcx.dep_graph().is_green(dep_node),
573 "fingerprint for green query instance not loaded from cache: {:?}",
577 debug!("BEGIN verify_ich({:?})", dep_node);
578 let new_hash = query.hash_result.map_or(Fingerprint::ZERO, |f| {
579 tcx.with_stable_hashing_context(|mut hcx| f(&mut hcx, result))
581 let old_hash = tcx.dep_graph().prev_fingerprint_of(dep_node);
582 debug!("END verify_ich({:?})", dep_node);
584 if Some(new_hash) != old_hash {
585 incremental_verify_ich_cold(tcx.sess(), DebugArg::from(&dep_node), DebugArg::from(&result));
589 // This DebugArg business is largely a mirror of std::fmt::ArgumentV1, which is
590 // currently not exposed publicly.
592 // The PR which added this attempted to use `&dyn Debug` instead, but that
593 // showed statistically significant worse compiler performance. It's not
594 // actually clear what the cause there was -- the code should be cold. If this
595 // can be replaced with `&dyn Debug` with on perf impact, then it probably
601 struct DebugArg<'a> {
603 fmt: fn(&Opaque, &mut std::fmt::Formatter<'_>) -> std::fmt::Result,
606 impl<'a, T> From<&'a T> for DebugArg<'a>
610 fn from(value: &'a T) -> DebugArg<'a> {
612 value: unsafe { std::mem::transmute(value) },
614 std::mem::transmute(<T as std::fmt::Debug>::fmt as fn(_, _) -> std::fmt::Result)
620 impl std::fmt::Debug for DebugArg<'_> {
621 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
622 (self.fmt)(self.value, f)
626 // Note that this is marked #[cold] and intentionally takes the equivalent of
627 // `dyn Debug` for its arguments, as we want to avoid generating a bunch of
628 // different implementations for LLVM to chew on (and filling up the final
631 fn incremental_verify_ich_cold(sess: &Session, dep_node: DebugArg<'_>, result: DebugArg<'_>) {
632 let run_cmd = if let Some(crate_name) = &sess.opts.crate_name {
633 format!("`cargo clean -p {}` or `cargo clean`", crate_name)
635 "`cargo clean`".to_string()
638 // When we emit an error message and panic, we try to debug-print the `DepNode`
639 // and query result. Unfortunately, this can cause us to run additional queries,
640 // which may result in another fingerprint mismatch while we're in the middle
641 // of processing this one. To avoid a double-panic (which kills the process
642 // before we can print out the query static), we print out a terse
643 // but 'safe' message if we detect a re-entrant call to this method.
645 static INSIDE_VERIFY_PANIC: Cell<bool> = const { Cell::new(false) };
648 let old_in_panic = INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.replace(true));
651 sess.emit_err(crate::error::Reentrant);
653 sess.emit_err(crate::error::IncrementCompilation {
655 dep_node: format!("{:?}", dep_node),
657 panic!("Found unstable fingerprints for {:?}: {:?}", dep_node, result);
660 INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.set(old_in_panic));
663 /// Ensure that either this query has all green inputs or been executed.
664 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
665 /// Returns true if the query should still run.
667 /// This function is particularly useful when executing passes for their
668 /// side-effects -- e.g., in order to report errors for erroneous programs.
670 /// Note: The optimization is only available during incr. comp.
672 fn ensure_must_run<CTX, K, V>(
675 query: &QueryVTable<CTX, K, V>,
676 ) -> (bool, Option<DepNode<CTX::DepKind>>)
678 K: crate::dep_graph::DepNodeParams<CTX::DepContext>,
681 if query.eval_always {
685 // Ensuring an anonymous query makes no sense
686 assert!(!query.anon);
688 let dep_node = query.to_dep_node(*tcx.dep_context(), key);
690 let dep_graph = tcx.dep_context().dep_graph();
691 match dep_graph.try_mark_green(tcx, &dep_node) {
693 // A None return from `try_mark_green` means that this is either
694 // a new dep node or that the dep node has already been marked red.
695 // Either way, we can't call `dep_graph.read()` as we don't have the
696 // DepNodeIndex. We must invoke the query itself. The performance cost
697 // this introduces should be negligible as we'll immediately hit the
698 // in-memory cache, or another query down the line will.
699 (true, Some(dep_node))
701 Some((_, dep_node_index)) => {
702 dep_graph.read_index(dep_node_index);
703 tcx.dep_context().profiler().query_cache_hit(dep_node_index.into());
715 pub fn get_query<Q, CTX>(tcx: CTX, span: Span, key: Q::Key, mode: QueryMode) -> Option<Q::Stored>
717 Q: QueryDescription<CTX>,
718 Q::Key: DepNodeParams<CTX::DepContext>,
719 Q::Value: Value<CTX::DepContext>,
722 let query = Q::make_vtable(tcx, &key);
723 let dep_node = if let QueryMode::Ensure = mode {
724 let (must_run, dep_node) = ensure_must_run(tcx, &key, &query);
733 let (result, dep_node_index) = try_execute_query(
742 if let Some(dep_node_index) = dep_node_index {
743 tcx.dep_context().dep_graph().read_index(dep_node_index)
748 pub fn force_query<Q, CTX>(tcx: CTX, key: Q::Key, dep_node: DepNode<CTX::DepKind>)
750 Q: QueryDescription<CTX>,
751 Q::Key: DepNodeParams<CTX::DepContext>,
752 Q::Value: Value<CTX::DepContext>,
755 // We may be concurrently trying both execute and force a query.
756 // Ensure that only one of them runs the query.
757 let cache = Q::query_cache(tcx);
758 let cached = cache.lookup(&key, |_, index| {
759 if std::intrinsics::unlikely(tcx.dep_context().profiler().enabled()) {
760 tcx.dep_context().profiler().query_cache_hit(index.into());
769 let query = Q::make_vtable(tcx, &key);
770 let state = Q::query_state(tcx);
771 debug_assert!(!query.anon);
773 try_execute_query(tcx, state, cache, DUMMY_SP, key, Some(dep_node), &query);