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