]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_system/src/query/plumbing.rs
Auto merge of #105127 - Sp00ph:const_new, r=dtolnay
[rust.git] / compiler / rustc_query_system / src / query / plumbing.rs
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.
4
5 use crate::dep_graph::{DepContext, DepNode, DepNodeIndex, DepNodeParams};
6 use crate::ich::StableHashingContext;
7 use crate::query::caches::QueryCache;
8 use crate::query::config::QueryVTable;
9 use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo};
10 use crate::query::{QueryContext, QueryMap, QuerySideEffects, QueryStackFrame};
11 use crate::values::Value;
12 use crate::HandleCycleError;
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 #[cfg(parallel_compiler)]
16 use rustc_data_structures::profiling::TimingGuard;
17 #[cfg(parallel_compiler)]
18 use rustc_data_structures::sharded::Sharded;
19 use rustc_data_structures::sync::Lock;
20 use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, FatalError};
21 use rustc_session::Session;
22 use rustc_span::{Span, DUMMY_SP};
23 use std::borrow::Borrow;
24 use std::cell::Cell;
25 use std::collections::hash_map::Entry;
26 use std::fmt::Debug;
27 use std::hash::Hash;
28 use std::mem;
29 use std::ptr;
30 use thin_vec::ThinVec;
31
32 use super::QueryConfig;
33
34 pub struct QueryState<K> {
35     #[cfg(parallel_compiler)]
36     active: Sharded<FxHashMap<K, QueryResult>>,
37     #[cfg(not(parallel_compiler))]
38     active: Lock<FxHashMap<K, QueryResult>>,
39 }
40
41 /// Indicates the state of a query for a given key in a query map.
42 enum QueryResult {
43     /// An already executing query. The query job can be used to await for its completion.
44     Started(QueryJob),
45
46     /// The query panicked. Queries trying to wait on this will raise a fatal error which will
47     /// silently panic.
48     Poisoned,
49 }
50
51 impl<K> QueryState<K>
52 where
53     K: Eq + Hash + Clone + Debug,
54 {
55     pub fn all_inactive(&self) -> bool {
56         #[cfg(parallel_compiler)]
57         {
58             let shards = self.active.lock_shards();
59             shards.iter().all(|shard| shard.is_empty())
60         }
61         #[cfg(not(parallel_compiler))]
62         {
63             self.active.lock().is_empty()
64         }
65     }
66
67     pub fn try_collect_active_jobs<Qcx: Copy>(
68         &self,
69         qcx: Qcx,
70         make_query: fn(Qcx, K) -> QueryStackFrame,
71         jobs: &mut QueryMap,
72     ) -> Option<()> {
73         #[cfg(parallel_compiler)]
74         {
75             // We use try_lock_shards here since we are called from the
76             // deadlock handler, and this shouldn't be locked.
77             let shards = self.active.try_lock_shards()?;
78             for shard in shards.iter() {
79                 for (k, v) in shard.iter() {
80                     if let QueryResult::Started(ref job) = *v {
81                         let query = make_query(qcx, k.clone());
82                         jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
83                     }
84                 }
85             }
86         }
87         #[cfg(not(parallel_compiler))]
88         {
89             // We use try_lock here since we are called from the
90             // deadlock handler, and this shouldn't be locked.
91             // (FIXME: Is this relevant for non-parallel compilers? It doesn't
92             // really hurt much.)
93             for (k, v) in self.active.try_lock()?.iter() {
94                 if let QueryResult::Started(ref job) = *v {
95                     let query = make_query(qcx, k.clone());
96                     jobs.insert(job.id, QueryJobInfo { query, job: job.clone() });
97                 }
98             }
99         }
100
101         Some(())
102     }
103 }
104
105 impl<K> Default for QueryState<K> {
106     fn default() -> QueryState<K> {
107         QueryState { active: Default::default() }
108     }
109 }
110
111 /// A type representing the responsibility to execute the job in the `job` field.
112 /// This will poison the relevant query if dropped.
113 struct JobOwner<'tcx, K>
114 where
115     K: Eq + Hash + Clone,
116 {
117     state: &'tcx QueryState<K>,
118     key: K,
119     id: QueryJobId,
120 }
121
122 #[cold]
123 #[inline(never)]
124 fn mk_cycle<Qcx, V, R>(
125     qcx: Qcx,
126     cycle_error: CycleError,
127     handler: HandleCycleError,
128     cache: &dyn crate::query::QueryStorage<Value = V, Stored = R>,
129 ) -> R
130 where
131     Qcx: QueryContext,
132     V: std::fmt::Debug + Value<Qcx::DepContext>,
133     R: Clone,
134 {
135     let error = report_cycle(qcx.dep_context().sess(), &cycle_error);
136     let value = handle_cycle_error(*qcx.dep_context(), &cycle_error, error, handler);
137     cache.store_nocache(value)
138 }
139
140 fn handle_cycle_error<Tcx, V>(
141     tcx: Tcx,
142     cycle_error: &CycleError,
143     mut error: DiagnosticBuilder<'_, ErrorGuaranteed>,
144     handler: HandleCycleError,
145 ) -> V
146 where
147     Tcx: DepContext,
148     V: Value<Tcx>,
149 {
150     use HandleCycleError::*;
151     match handler {
152         Error => {
153             error.emit();
154             Value::from_cycle_error(tcx, &cycle_error.cycle)
155         }
156         Fatal => {
157             error.emit();
158             tcx.sess().abort_if_errors();
159             unreachable!()
160         }
161         DelayBug => {
162             error.delay_as_bug();
163             Value::from_cycle_error(tcx, &cycle_error.cycle)
164         }
165     }
166 }
167
168 impl<'tcx, K> JobOwner<'tcx, K>
169 where
170     K: Eq + Hash + Clone,
171 {
172     /// Either gets a `JobOwner` corresponding the query, allowing us to
173     /// start executing the query, or returns with the result of the query.
174     /// This function assumes that `try_get_cached` is already called and returned `lookup`.
175     /// If the query is executing elsewhere, this will wait for it and return the result.
176     /// If the query panicked, this will silently panic.
177     ///
178     /// This function is inlined because that results in a noticeable speed-up
179     /// for some compile-time benchmarks.
180     #[inline(always)]
181     fn try_start<'b, Qcx>(
182         qcx: &'b Qcx,
183         state: &'b QueryState<K>,
184         span: Span,
185         key: K,
186     ) -> TryGetJob<'b, K>
187     where
188         Qcx: QueryContext,
189     {
190         #[cfg(parallel_compiler)]
191         let mut state_lock = state.active.get_shard_by_value(&key).lock();
192         #[cfg(not(parallel_compiler))]
193         let mut state_lock = state.active.lock();
194         let lock = &mut *state_lock;
195
196         match lock.entry(key) {
197             Entry::Vacant(entry) => {
198                 let id = qcx.next_job_id();
199                 let job = qcx.current_query_job();
200                 let job = QueryJob::new(id, span, job);
201
202                 let key = entry.key().clone();
203                 entry.insert(QueryResult::Started(job));
204
205                 let owner = JobOwner { state, id, key };
206                 return TryGetJob::NotYetStarted(owner);
207             }
208             Entry::Occupied(mut entry) => {
209                 match entry.get_mut() {
210                     #[cfg(not(parallel_compiler))]
211                     QueryResult::Started(job) => {
212                         let id = job.id;
213                         drop(state_lock);
214
215                         // If we are single-threaded we know that we have cycle error,
216                         // so we just return the error.
217                         return TryGetJob::Cycle(id.find_cycle_in_stack(
218                             qcx.try_collect_active_jobs().unwrap(),
219                             &qcx.current_query_job(),
220                             span,
221                         ));
222                     }
223                     #[cfg(parallel_compiler)]
224                     QueryResult::Started(job) => {
225                         // For parallel queries, we'll block and wait until the query running
226                         // in another thread has completed. Record how long we wait in the
227                         // self-profiler.
228                         let query_blocked_prof_timer = qcx.dep_context().profiler().query_blocked();
229
230                         // Get the latch out
231                         let latch = job.latch();
232
233                         drop(state_lock);
234
235                         // With parallel queries we might just have to wait on some other
236                         // thread.
237                         let result = latch.wait_on(qcx.current_query_job(), span);
238
239                         match result {
240                             Ok(()) => TryGetJob::JobCompleted(query_blocked_prof_timer),
241                             Err(cycle) => TryGetJob::Cycle(cycle),
242                         }
243                     }
244                     QueryResult::Poisoned => FatalError.raise(),
245                 }
246             }
247         }
248     }
249
250     /// Completes the query by updating the query cache with the `result`,
251     /// signals the waiter and forgets the JobOwner, so it won't poison the query
252     fn complete<C>(self, cache: &C, result: C::Value, dep_node_index: DepNodeIndex) -> C::Stored
253     where
254         C: QueryCache<Key = K>,
255     {
256         // We can move out of `self` here because we `mem::forget` it below
257         let key = unsafe { ptr::read(&self.key) };
258         let state = self.state;
259
260         // Forget ourself so our destructor won't poison the query
261         mem::forget(self);
262
263         let (job, result) = {
264             let job = {
265                 #[cfg(parallel_compiler)]
266                 let mut lock = state.active.get_shard_by_value(&key).lock();
267                 #[cfg(not(parallel_compiler))]
268                 let mut lock = state.active.lock();
269                 match lock.remove(&key).unwrap() {
270                     QueryResult::Started(job) => job,
271                     QueryResult::Poisoned => panic!(),
272                 }
273             };
274             let result = cache.complete(key, result, dep_node_index);
275             (job, result)
276         };
277
278         job.signal_complete();
279         result
280     }
281 }
282
283 impl<'tcx, K> Drop for JobOwner<'tcx, K>
284 where
285     K: Eq + Hash + Clone,
286 {
287     #[inline(never)]
288     #[cold]
289     fn drop(&mut self) {
290         // Poison the query so jobs waiting on it panic.
291         let state = self.state;
292         let job = {
293             #[cfg(parallel_compiler)]
294             let mut shard = state.active.get_shard_by_value(&self.key).lock();
295             #[cfg(not(parallel_compiler))]
296             let mut shard = state.active.lock();
297             let job = match shard.remove(&self.key).unwrap() {
298                 QueryResult::Started(job) => job,
299                 QueryResult::Poisoned => panic!(),
300             };
301             shard.insert(self.key.clone(), QueryResult::Poisoned);
302             job
303         };
304         // Also signal the completion of the job, so waiters
305         // will continue execution.
306         job.signal_complete();
307     }
308 }
309
310 #[derive(Clone)]
311 pub(crate) struct CycleError {
312     /// The query and related span that uses the cycle.
313     pub usage: Option<(Span, QueryStackFrame)>,
314     pub cycle: Vec<QueryInfo>,
315 }
316
317 /// The result of `try_start`.
318 enum TryGetJob<'tcx, K>
319 where
320     K: Eq + Hash + Clone,
321 {
322     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
323     NotYetStarted(JobOwner<'tcx, K>),
324
325     /// The query was already completed.
326     /// Returns the result of the query and its dep-node index
327     /// if it succeeded or a cycle error if it failed.
328     #[cfg(parallel_compiler)]
329     JobCompleted(TimingGuard<'tcx>),
330
331     /// Trying to execute the query resulted in a cycle.
332     Cycle(CycleError),
333 }
334
335 /// Checks if the query is already computed and in the cache.
336 /// It returns the shard index and a lock guard to the shard,
337 /// which will be used if the query is not in the cache and we need
338 /// to compute it.
339 #[inline]
340 pub fn try_get_cached<'a, Tcx, C, R, OnHit>(
341     tcx: Tcx,
342     cache: &'a C,
343     key: &C::Key,
344     // `on_hit` can be called while holding a lock to the query cache
345     on_hit: OnHit,
346 ) -> Result<R, ()>
347 where
348     C: QueryCache,
349     Tcx: DepContext,
350     OnHit: FnOnce(&C::Stored) -> R,
351 {
352     cache.lookup(&key, |value, index| {
353         if std::intrinsics::unlikely(tcx.profiler().enabled()) {
354             tcx.profiler().query_cache_hit(index.into());
355         }
356         tcx.dep_graph().read_index(index);
357         on_hit(value)
358     })
359 }
360
361 fn try_execute_query<Qcx, C>(
362     qcx: Qcx,
363     state: &QueryState<C::Key>,
364     cache: &C,
365     span: Span,
366     key: C::Key,
367     dep_node: Option<DepNode<Qcx::DepKind>>,
368     query: &QueryVTable<Qcx, C::Key, C::Value>,
369 ) -> (C::Stored, Option<DepNodeIndex>)
370 where
371     C: QueryCache,
372     C::Key: Clone + DepNodeParams<Qcx::DepContext>,
373     C::Value: Value<Qcx::DepContext>,
374     C::Stored: Debug + std::borrow::Borrow<C::Value>,
375     Qcx: QueryContext,
376 {
377     match JobOwner::<'_, C::Key>::try_start(&qcx, state, span, key.clone()) {
378         TryGetJob::NotYetStarted(job) => {
379             let (result, dep_node_index) = execute_job(qcx, key.clone(), dep_node, query, job.id);
380             if query.feedable {
381                 // We may have put a value inside the cache from inside the execution.
382                 // Verify that it has the same hash as what we have now, to ensure consistency.
383                 let _ = cache.lookup(&key, |cached_result, _| {
384                     let hasher = query.hash_result.expect("feedable forbids no_hash");
385                     let old_hash = qcx.dep_context().with_stable_hashing_context(|mut hcx| hasher(&mut hcx, cached_result.borrow()));
386                     let new_hash = qcx.dep_context().with_stable_hashing_context(|mut hcx| hasher(&mut hcx, &result));
387                     debug_assert_eq!(
388                         old_hash, new_hash,
389                         "Computed query value for {:?}({:?}) is inconsistent with fed value,\ncomputed={:#?}\nfed={:#?}",
390                         query.dep_kind, key, result, cached_result,
391                     );
392                 });
393             }
394             let result = job.complete(cache, result, dep_node_index);
395             (result, Some(dep_node_index))
396         }
397         TryGetJob::Cycle(error) => {
398             let result = mk_cycle(qcx, error, query.handle_cycle_error, cache);
399             (result, None)
400         }
401         #[cfg(parallel_compiler)]
402         TryGetJob::JobCompleted(query_blocked_prof_timer) => {
403             let (v, index) = cache
404                 .lookup(&key, |value, index| (value.clone(), index))
405                 .unwrap_or_else(|_| panic!("value must be in cache after waiting"));
406
407             if std::intrinsics::unlikely(qcx.dep_context().profiler().enabled()) {
408                 qcx.dep_context().profiler().query_cache_hit(index.into());
409             }
410             query_blocked_prof_timer.finish_with_query_invocation_id(index.into());
411
412             (v, Some(index))
413         }
414     }
415 }
416
417 fn execute_job<Qcx, K, V>(
418     qcx: Qcx,
419     key: K,
420     mut dep_node_opt: Option<DepNode<Qcx::DepKind>>,
421     query: &QueryVTable<Qcx, K, V>,
422     job_id: QueryJobId,
423 ) -> (V, DepNodeIndex)
424 where
425     K: Clone + DepNodeParams<Qcx::DepContext>,
426     V: Debug,
427     Qcx: QueryContext,
428 {
429     let dep_graph = qcx.dep_context().dep_graph();
430
431     // Fast path for when incr. comp. is off.
432     if !dep_graph.is_fully_enabled() {
433         let prof_timer = qcx.dep_context().profiler().query_provider();
434         let result = qcx.start_query(job_id, query.depth_limit, None, || {
435             query.compute(*qcx.dep_context(), key)
436         });
437         let dep_node_index = dep_graph.next_virtual_depnode_index();
438         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
439         return (result, dep_node_index);
440     }
441
442     if !query.anon && !query.eval_always {
443         // `to_dep_node` is expensive for some `DepKind`s.
444         let dep_node =
445             dep_node_opt.get_or_insert_with(|| query.to_dep_node(*qcx.dep_context(), &key));
446
447         // The diagnostics for this query will be promoted to the current session during
448         // `try_mark_green()`, so we can ignore them here.
449         if let Some(ret) = qcx.start_query(job_id, false, None, || {
450             try_load_from_disk_and_cache_in_memory(qcx, &key, &dep_node, query)
451         }) {
452             return ret;
453         }
454     }
455
456     let prof_timer = qcx.dep_context().profiler().query_provider();
457     let diagnostics = Lock::new(ThinVec::new());
458
459     let (result, dep_node_index) =
460         qcx.start_query(job_id, query.depth_limit, Some(&diagnostics), || {
461             if query.anon {
462                 return dep_graph.with_anon_task(*qcx.dep_context(), query.dep_kind, || {
463                     query.compute(*qcx.dep_context(), key)
464                 });
465             }
466
467             // `to_dep_node` is expensive for some `DepKind`s.
468             let dep_node =
469                 dep_node_opt.unwrap_or_else(|| query.to_dep_node(*qcx.dep_context(), &key));
470
471             dep_graph.with_task(dep_node, *qcx.dep_context(), key, query.compute, query.hash_result)
472         });
473
474     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
475
476     let diagnostics = diagnostics.into_inner();
477     let side_effects = QuerySideEffects { diagnostics };
478
479     if std::intrinsics::unlikely(!side_effects.is_empty()) {
480         if query.anon {
481             qcx.store_side_effects_for_anon_node(dep_node_index, side_effects);
482         } else {
483             qcx.store_side_effects(dep_node_index, side_effects);
484         }
485     }
486
487     (result, dep_node_index)
488 }
489
490 fn try_load_from_disk_and_cache_in_memory<Qcx, K, V>(
491     qcx: Qcx,
492     key: &K,
493     dep_node: &DepNode<Qcx::DepKind>,
494     query: &QueryVTable<Qcx, K, V>,
495 ) -> Option<(V, DepNodeIndex)>
496 where
497     K: Clone,
498     Qcx: QueryContext,
499     V: Debug,
500 {
501     // Note this function can be called concurrently from the same query
502     // We must ensure that this is handled correctly.
503
504     let dep_graph = qcx.dep_context().dep_graph();
505     let (prev_dep_node_index, dep_node_index) = dep_graph.try_mark_green(qcx, &dep_node)?;
506
507     debug_assert!(dep_graph.is_green(dep_node));
508
509     // First we try to load the result from the on-disk cache.
510     // Some things are never cached on disk.
511     if let Some(try_load_from_disk) = query.try_load_from_disk {
512         let prof_timer = qcx.dep_context().profiler().incr_cache_loading();
513
514         // The call to `with_query_deserialization` enforces that no new `DepNodes`
515         // are created during deserialization. See the docs of that method for more
516         // details.
517         let result =
518             dep_graph.with_query_deserialization(|| try_load_from_disk(qcx, prev_dep_node_index));
519
520         prof_timer.finish_with_query_invocation_id(dep_node_index.into());
521
522         if let Some(result) = result {
523             if std::intrinsics::unlikely(
524                 qcx.dep_context().sess().opts.unstable_opts.query_dep_graph,
525             ) {
526                 dep_graph.mark_debug_loaded_from_disk(*dep_node)
527             }
528
529             let prev_fingerprint = qcx
530                 .dep_context()
531                 .dep_graph()
532                 .prev_fingerprint_of(dep_node)
533                 .unwrap_or(Fingerprint::ZERO);
534             // If `-Zincremental-verify-ich` is specified, re-hash results from
535             // the cache and make sure that they have the expected fingerprint.
536             //
537             // If not, we still seek to verify a subset of fingerprints loaded
538             // from disk. Re-hashing results is fairly expensive, so we can't
539             // currently afford to verify every hash. This subset should still
540             // give us some coverage of potential bugs though.
541             let try_verify = prev_fingerprint.as_value().1 % 32 == 0;
542             if std::intrinsics::unlikely(
543                 try_verify || qcx.dep_context().sess().opts.unstable_opts.incremental_verify_ich,
544             ) {
545                 incremental_verify_ich(*qcx.dep_context(), &result, dep_node, query.hash_result);
546             }
547
548             return Some((result, dep_node_index));
549         }
550
551         // We always expect to find a cached result for things that
552         // can be forced from `DepNode`.
553         debug_assert!(
554             !qcx.dep_context().fingerprint_style(dep_node.kind).reconstructible(),
555             "missing on-disk cache entry for {:?}",
556             dep_node
557         );
558     }
559
560     // We could not load a result from the on-disk cache, so
561     // recompute.
562     let prof_timer = qcx.dep_context().profiler().query_provider();
563
564     // The dep-graph for this computation is already in-place.
565     let result = dep_graph.with_ignore(|| query.compute(*qcx.dep_context(), key.clone()));
566
567     prof_timer.finish_with_query_invocation_id(dep_node_index.into());
568
569     // Verify that re-running the query produced a result with the expected hash
570     // This catches bugs in query implementations, turning them into ICEs.
571     // For example, a query might sort its result by `DefId` - since `DefId`s are
572     // not stable across compilation sessions, the result could get up getting sorted
573     // in a different order when the query is re-run, even though all of the inputs
574     // (e.g. `DefPathHash` values) were green.
575     //
576     // See issue #82920 for an example of a miscompilation that would get turned into
577     // an ICE by this check
578     incremental_verify_ich(*qcx.dep_context(), &result, dep_node, query.hash_result);
579
580     Some((result, dep_node_index))
581 }
582
583 #[instrument(skip(tcx, result, hash_result), level = "debug")]
584 pub(crate) fn incremental_verify_ich<Tcx, V: Debug>(
585     tcx: Tcx,
586     result: &V,
587     dep_node: &DepNode<Tcx::DepKind>,
588     hash_result: Option<fn(&mut StableHashingContext<'_>, &V) -> Fingerprint>,
589 ) -> Fingerprint
590 where
591     Tcx: DepContext,
592 {
593     assert!(
594         tcx.dep_graph().is_green(dep_node),
595         "fingerprint for green query instance not loaded from cache: {:?}",
596         dep_node,
597     );
598
599     let new_hash = hash_result.map_or(Fingerprint::ZERO, |f| {
600         tcx.with_stable_hashing_context(|mut hcx| f(&mut hcx, result))
601     });
602
603     let old_hash = tcx.dep_graph().prev_fingerprint_of(dep_node);
604
605     if Some(new_hash) != old_hash {
606         incremental_verify_ich_failed(
607             tcx.sess(),
608             DebugArg::from(&dep_node),
609             DebugArg::from(&result),
610         );
611     }
612
613     new_hash
614 }
615
616 // This DebugArg business is largely a mirror of std::fmt::ArgumentV1, which is
617 // currently not exposed publicly.
618 //
619 // The PR which added this attempted to use `&dyn Debug` instead, but that
620 // showed statistically significant worse compiler performance. It's not
621 // actually clear what the cause there was -- the code should be cold. If this
622 // can be replaced with `&dyn Debug` with on perf impact, then it probably
623 // should be.
624 extern "C" {
625     type Opaque;
626 }
627
628 struct DebugArg<'a> {
629     value: &'a Opaque,
630     fmt: fn(&Opaque, &mut std::fmt::Formatter<'_>) -> std::fmt::Result,
631 }
632
633 impl<'a, T> From<&'a T> for DebugArg<'a>
634 where
635     T: std::fmt::Debug,
636 {
637     fn from(value: &'a T) -> DebugArg<'a> {
638         DebugArg {
639             value: unsafe { std::mem::transmute(value) },
640             fmt: unsafe {
641                 std::mem::transmute(<T as std::fmt::Debug>::fmt as fn(_, _) -> std::fmt::Result)
642             },
643         }
644     }
645 }
646
647 impl std::fmt::Debug for DebugArg<'_> {
648     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649         (self.fmt)(self.value, f)
650     }
651 }
652
653 // Note that this is marked #[cold] and intentionally takes the equivalent of
654 // `dyn Debug` for its arguments, as we want to avoid generating a bunch of
655 // different implementations for LLVM to chew on (and filling up the final
656 // binary, too).
657 #[cold]
658 fn incremental_verify_ich_failed(sess: &Session, dep_node: DebugArg<'_>, result: DebugArg<'_>) {
659     // When we emit an error message and panic, we try to debug-print the `DepNode`
660     // and query result. Unfortunately, this can cause us to run additional queries,
661     // which may result in another fingerprint mismatch while we're in the middle
662     // of processing this one. To avoid a double-panic (which kills the process
663     // before we can print out the query static), we print out a terse
664     // but 'safe' message if we detect a re-entrant call to this method.
665     thread_local! {
666         static INSIDE_VERIFY_PANIC: Cell<bool> = const { Cell::new(false) };
667     };
668
669     let old_in_panic = INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.replace(true));
670
671     if old_in_panic {
672         sess.emit_err(crate::error::Reentrant);
673     } else {
674         let run_cmd = if let Some(crate_name) = &sess.opts.crate_name {
675             format!("`cargo clean -p {}` or `cargo clean`", crate_name)
676         } else {
677             "`cargo clean`".to_string()
678         };
679
680         sess.emit_err(crate::error::IncrementCompilation {
681             run_cmd,
682             dep_node: format!("{:?}", dep_node),
683         });
684         panic!("Found unstable fingerprints for {:?}: {:?}", dep_node, result);
685     }
686
687     INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.set(old_in_panic));
688 }
689
690 /// Ensure that either this query has all green inputs or been executed.
691 /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
692 /// Returns true if the query should still run.
693 ///
694 /// This function is particularly useful when executing passes for their
695 /// side-effects -- e.g., in order to report errors for erroneous programs.
696 ///
697 /// Note: The optimization is only available during incr. comp.
698 #[inline(never)]
699 fn ensure_must_run<Qcx, K, V>(
700     qcx: Qcx,
701     key: &K,
702     query: &QueryVTable<Qcx, K, V>,
703 ) -> (bool, Option<DepNode<Qcx::DepKind>>)
704 where
705     K: crate::dep_graph::DepNodeParams<Qcx::DepContext>,
706     Qcx: QueryContext,
707 {
708     if query.eval_always {
709         return (true, None);
710     }
711
712     // Ensuring an anonymous query makes no sense
713     assert!(!query.anon);
714
715     let dep_node = query.to_dep_node(*qcx.dep_context(), key);
716
717     let dep_graph = qcx.dep_context().dep_graph();
718     match dep_graph.try_mark_green(qcx, &dep_node) {
719         None => {
720             // A None return from `try_mark_green` means that this is either
721             // a new dep node or that the dep node has already been marked red.
722             // Either way, we can't call `dep_graph.read()` as we don't have the
723             // DepNodeIndex. We must invoke the query itself. The performance cost
724             // this introduces should be negligible as we'll immediately hit the
725             // in-memory cache, or another query down the line will.
726             (true, Some(dep_node))
727         }
728         Some((_, dep_node_index)) => {
729             dep_graph.read_index(dep_node_index);
730             qcx.dep_context().profiler().query_cache_hit(dep_node_index.into());
731             (false, None)
732         }
733     }
734 }
735
736 #[derive(Debug)]
737 pub enum QueryMode {
738     Get,
739     Ensure,
740 }
741
742 pub fn get_query<Q, Qcx>(qcx: Qcx, span: Span, key: Q::Key, mode: QueryMode) -> Option<Q::Stored>
743 where
744     Q: QueryConfig<Qcx>,
745     Q::Key: DepNodeParams<Qcx::DepContext>,
746     Q::Value: Value<Qcx::DepContext>,
747     Qcx: QueryContext,
748 {
749     let query = Q::make_vtable(qcx, &key);
750     let dep_node = if let QueryMode::Ensure = mode {
751         let (must_run, dep_node) = ensure_must_run(qcx, &key, &query);
752         if !must_run {
753             return None;
754         }
755         dep_node
756     } else {
757         None
758     };
759
760     let (result, dep_node_index) = try_execute_query(
761         qcx,
762         Q::query_state(qcx),
763         Q::query_cache(qcx),
764         span,
765         key,
766         dep_node,
767         &query,
768     );
769     if let Some(dep_node_index) = dep_node_index {
770         qcx.dep_context().dep_graph().read_index(dep_node_index)
771     }
772     Some(result)
773 }
774
775 pub fn force_query<Q, Qcx>(qcx: Qcx, key: Q::Key, dep_node: DepNode<Qcx::DepKind>)
776 where
777     Q: QueryConfig<Qcx>,
778     Q::Key: DepNodeParams<Qcx::DepContext>,
779     Q::Value: Value<Qcx::DepContext>,
780     Qcx: QueryContext,
781 {
782     // We may be concurrently trying both execute and force a query.
783     // Ensure that only one of them runs the query.
784     let cache = Q::query_cache(qcx);
785     let cached = cache.lookup(&key, |_, index| {
786         if std::intrinsics::unlikely(qcx.dep_context().profiler().enabled()) {
787             qcx.dep_context().profiler().query_cache_hit(index.into());
788         }
789     });
790
791     match cached {
792         Ok(()) => return,
793         Err(()) => {}
794     }
795
796     let query = Q::make_vtable(qcx, &key);
797     let state = Q::query_state(qcx);
798     debug_assert!(!query.anon);
799
800     try_execute_query(qcx, state, cache, DUMMY_SP, key, Some(dep_node), &query);
801 }