]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/query/plumbing.rs
Rollup merge of #68006 - infinity0:master, r=nikomatsakis
[rust.git] / src / librustc / ty / 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::{DepKind, DepNode, DepNodeIndex, SerializedDepNodeIndex};
6 use crate::ty::query::config::{QueryConfig, QueryDescription};
7 use crate::ty::query::job::{QueryInfo, QueryJob};
8 use crate::ty::query::Query;
9 use crate::ty::tls;
10 use crate::ty::{self, TyCtxt};
11
12 use errors::{struct_span_err, Diagnostic, DiagnosticBuilder, FatalError, Handler, Level};
13 #[cfg(not(parallel_compiler))]
14 use rustc_data_structures::cold_path;
15 use rustc_data_structures::fx::{FxHashMap, FxHasher};
16 use rustc_data_structures::sharded::Sharded;
17 use rustc_data_structures::sync::{Lock, Lrc};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use rustc_span::source_map::DUMMY_SP;
20 use rustc_span::Span;
21 use std::collections::hash_map::Entry;
22 use std::hash::{Hash, Hasher};
23 use std::mem;
24 use std::ptr;
25
26 use rustc_error_codes::*;
27
28 pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
29     pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
30     pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
31     #[cfg(debug_assertions)]
32     pub(super) cache_hits: usize,
33 }
34
35 pub(super) struct QueryValue<T> {
36     pub(super) value: T,
37     pub(super) index: DepNodeIndex,
38 }
39
40 impl<T> QueryValue<T> {
41     pub(super) fn new(value: T, dep_node_index: DepNodeIndex) -> QueryValue<T> {
42         QueryValue { value, index: dep_node_index }
43     }
44 }
45
46 /// Indicates the state of a query for a given key in a query map.
47 pub(super) enum QueryResult<'tcx> {
48     /// An already executing query. The query job can be used to await for its completion.
49     Started(Lrc<QueryJob<'tcx>>),
50
51     /// The query panicked. Queries trying to wait on this will raise a fatal error or
52     /// silently panic.
53     Poisoned,
54 }
55
56 impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
57     fn default() -> QueryCache<'tcx, M> {
58         QueryCache {
59             results: FxHashMap::default(),
60             active: FxHashMap::default(),
61             #[cfg(debug_assertions)]
62             cache_hits: 0,
63         }
64     }
65 }
66
67 /// A type representing the responsibility to execute the job in the `job` field.
68 /// This will poison the relevant query if dropped.
69 pub(super) struct JobOwner<'a, 'tcx, Q: QueryDescription<'tcx>> {
70     cache: &'a Sharded<QueryCache<'tcx, Q>>,
71     key: Q::Key,
72     job: Lrc<QueryJob<'tcx>>,
73 }
74
75 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
76     /// Either gets a `JobOwner` corresponding the query, allowing us to
77     /// start executing the query, or returns with the result of the query.
78     /// If the query is executing elsewhere, this will wait for it.
79     /// If the query panicked, this will silently panic.
80     ///
81     /// This function is inlined because that results in a noticeable speed-up
82     /// for some compile-time benchmarks.
83     #[inline(always)]
84     pub(super) fn try_get(tcx: TyCtxt<'tcx>, span: Span, key: &Q::Key) -> TryGetJob<'a, 'tcx, Q> {
85         let cache = Q::query_cache(tcx);
86         loop {
87             // We compute the key's hash once and then use it for both the
88             // shard lookup and the hashmap lookup. This relies on the fact
89             // that both of them use `FxHasher`.
90             let mut state = FxHasher::default();
91             key.hash(&mut state);
92             let key_hash = state.finish();
93
94             let mut lock = cache.get_shard_by_hash(key_hash).lock();
95             if let Some((_, value)) =
96                 lock.results.raw_entry().from_key_hashed_nocheck(key_hash, key)
97             {
98                 tcx.prof.query_cache_hit(Q::NAME);
99                 let result = (value.value.clone(), value.index);
100                 #[cfg(debug_assertions)]
101                 {
102                     lock.cache_hits += 1;
103                 }
104                 return TryGetJob::JobCompleted(result);
105             }
106
107             #[cfg(parallel_compiler)]
108             let query_blocked_prof_timer;
109
110             let job = match lock.active.entry((*key).clone()) {
111                 Entry::Occupied(entry) => {
112                     match *entry.get() {
113                         QueryResult::Started(ref job) => {
114                             // For parallel queries, we'll block and wait until the query running
115                             // in another thread has completed. Record how long we wait in the
116                             // self-profiler.
117                             #[cfg(parallel_compiler)]
118                             {
119                                 query_blocked_prof_timer = tcx.prof.query_blocked(Q::NAME);
120                             }
121
122                             job.clone()
123                         }
124                         QueryResult::Poisoned => FatalError.raise(),
125                     }
126                 }
127                 Entry::Vacant(entry) => {
128                     // No job entry for this query. Return a new one to be started later.
129                     return tls::with_related_context(tcx, |icx| {
130                         // Create the `parent` variable before `info`. This allows LLVM
131                         // to elide the move of `info`
132                         let parent = icx.query.clone();
133                         let info = QueryInfo { span, query: Q::query(key.clone()) };
134                         let job = Lrc::new(QueryJob::new(info, parent));
135                         let owner = JobOwner { cache, job: job.clone(), key: (*key).clone() };
136                         entry.insert(QueryResult::Started(job));
137                         TryGetJob::NotYetStarted(owner)
138                     });
139                 }
140             };
141             mem::drop(lock);
142
143             // If we are single-threaded we know that we have cycle error,
144             // so we just return the error.
145             #[cfg(not(parallel_compiler))]
146             return TryGetJob::Cycle(cold_path(|| {
147                 Q::handle_cycle_error(tcx, job.find_cycle_in_stack(tcx, span))
148             }));
149
150             // With parallel queries we might just have to wait on some other
151             // thread.
152             #[cfg(parallel_compiler)]
153             {
154                 let result = job.r#await(tcx, span);
155
156                 // This `drop()` is not strictly necessary as the binding
157                 // would go out of scope anyway. But it's good to have an
158                 // explicit marker of how far the measurement goes.
159                 drop(query_blocked_prof_timer);
160
161                 if let Err(cycle) = result {
162                     return TryGetJob::Cycle(Q::handle_cycle_error(tcx, cycle));
163                 }
164             }
165         }
166     }
167
168     /// Completes the query by updating the query cache with the `result`,
169     /// signals the waiter and forgets the JobOwner, so it won't poison the query
170     #[inline(always)]
171     pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
172         // We can move out of `self` here because we `mem::forget` it below
173         let key = unsafe { ptr::read(&self.key) };
174         let job = unsafe { ptr::read(&self.job) };
175         let cache = self.cache;
176
177         // Forget ourself so our destructor won't poison the query
178         mem::forget(self);
179
180         let value = QueryValue::new(result.clone(), dep_node_index);
181         {
182             let mut lock = cache.get_shard_by_value(&key).lock();
183             lock.active.remove(&key);
184             lock.results.insert(key, value);
185         }
186
187         job.signal_complete();
188     }
189 }
190
191 #[inline(always)]
192 fn with_diagnostics<F, R>(f: F) -> (R, ThinVec<Diagnostic>)
193 where
194     F: FnOnce(Option<&Lock<ThinVec<Diagnostic>>>) -> R,
195 {
196     let diagnostics = Lock::new(ThinVec::new());
197     let result = f(Some(&diagnostics));
198     (result, diagnostics.into_inner())
199 }
200
201 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
202     #[inline(never)]
203     #[cold]
204     fn drop(&mut self) {
205         // Poison the query so jobs waiting on it panic.
206         let shard = self.cache.get_shard_by_value(&self.key);
207         shard.lock().active.insert(self.key.clone(), QueryResult::Poisoned);
208         // Also signal the completion of the job, so waiters
209         // will continue execution.
210         self.job.signal_complete();
211     }
212 }
213
214 #[derive(Clone)]
215 pub struct CycleError<'tcx> {
216     /// The query and related span that uses the cycle.
217     pub(super) usage: Option<(Span, Query<'tcx>)>,
218     pub(super) cycle: Vec<QueryInfo<'tcx>>,
219 }
220
221 /// The result of `try_get_lock`.
222 pub(super) enum TryGetJob<'a, 'tcx, D: QueryDescription<'tcx>> {
223     /// The query is not yet started. Contains a guard to the cache eventually used to start it.
224     NotYetStarted(JobOwner<'a, 'tcx, D>),
225
226     /// The query was already completed.
227     /// Returns the result of the query and its dep-node index
228     /// if it succeeded or a cycle error if it failed.
229     JobCompleted((D::Value, DepNodeIndex)),
230
231     /// Trying to execute the query resulted in a cycle.
232     Cycle(D::Value),
233 }
234
235 impl<'tcx> TyCtxt<'tcx> {
236     /// Executes a job by changing the `ImplicitCtxt` to point to the
237     /// new query job while it executes. It returns the diagnostics
238     /// captured during execution and the actual result.
239     #[inline(always)]
240     pub(super) fn start_query<F, R>(
241         self,
242         job: Lrc<QueryJob<'tcx>>,
243         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
244         compute: F,
245     ) -> R
246     where
247         F: FnOnce(TyCtxt<'tcx>) -> R,
248     {
249         // The `TyCtxt` stored in TLS has the same global interner lifetime
250         // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
251         // when accessing the `ImplicitCtxt`.
252         tls::with_related_context(self, move |current_icx| {
253             // Update the `ImplicitCtxt` to point to our new query job.
254             let new_icx = tls::ImplicitCtxt {
255                 tcx: self,
256                 query: Some(job),
257                 diagnostics,
258                 layout_depth: current_icx.layout_depth,
259                 task_deps: current_icx.task_deps,
260             };
261
262             // Use the `ImplicitCtxt` while we execute the query.
263             tls::enter_context(&new_icx, |_| compute(self))
264         })
265     }
266
267     #[inline(never)]
268     #[cold]
269     pub(super) fn report_cycle(
270         self,
271         CycleError { usage, cycle: stack }: CycleError<'tcx>,
272     ) -> DiagnosticBuilder<'tcx> {
273         assert!(!stack.is_empty());
274
275         let fix_span = |span: Span, query: &Query<'tcx>| {
276             self.sess.source_map().def_span(query.default_span(self, span))
277         };
278
279         // Disable naming impls with types in this path, since that
280         // sometimes cycles itself, leading to extra cycle errors.
281         // (And cycle errors around impls tend to occur during the
282         // collect/coherence phases anyhow.)
283         ty::print::with_forced_impl_filename_line(|| {
284             let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
285             let mut err = struct_span_err!(
286                 self.sess,
287                 span,
288                 E0391,
289                 "cycle detected when {}",
290                 stack[0].query.describe(self)
291             );
292
293             for i in 1..stack.len() {
294                 let query = &stack[i].query;
295                 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
296                 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
297             }
298
299             err.note(&format!(
300                 "...which again requires {}, completing the cycle",
301                 stack[0].query.describe(self)
302             ));
303
304             if let Some((span, query)) = usage {
305                 err.span_note(
306                     fix_span(span, &query),
307                     &format!("cycle used when {}", query.describe(self)),
308                 );
309             }
310
311             err
312         })
313     }
314
315     pub fn try_print_query_stack(handler: &Handler) {
316         eprintln!("query stack during panic:");
317
318         // Be careful reyling on global state here: this code is called from
319         // a panic hook, which means that the global `Handler` may be in a weird
320         // state if it was responsible for triggering the panic.
321         tls::with_context_opt(|icx| {
322             if let Some(icx) = icx {
323                 let mut current_query = icx.query.clone();
324                 let mut i = 0;
325
326                 while let Some(query) = current_query {
327                     let mut diag = Diagnostic::new(
328                         Level::FailureNote,
329                         &format!(
330                             "#{} [{}] {}",
331                             i,
332                             query.info.query.name(),
333                             query.info.query.describe(icx.tcx)
334                         ),
335                     );
336                     diag.span = icx.tcx.sess.source_map().def_span(query.info.span).into();
337                     handler.force_print_diagnostic(diag);
338
339                     current_query = query.parent.clone();
340                     i += 1;
341                 }
342             }
343         });
344
345         eprintln!("end of query stack");
346     }
347
348     #[inline(never)]
349     pub(super) fn get_query<Q: QueryDescription<'tcx>>(self, span: Span, key: Q::Key) -> Q::Value {
350         debug!("ty::query::get_query<{}>(key={:?}, span={:?})", Q::NAME.as_str(), key, span);
351
352         let job = match JobOwner::try_get(self, span, &key) {
353             TryGetJob::NotYetStarted(job) => job,
354             TryGetJob::Cycle(result) => return result,
355             TryGetJob::JobCompleted((v, index)) => {
356                 self.dep_graph.read_index(index);
357                 return v;
358             }
359         };
360
361         // Fast path for when incr. comp. is off. `to_dep_node` is
362         // expensive for some `DepKind`s.
363         if !self.dep_graph.is_fully_enabled() {
364             let null_dep_node = DepNode::new_no_params(crate::dep_graph::DepKind::Null);
365             return self.force_query_with_job::<Q>(key, job, null_dep_node).0;
366         }
367
368         if Q::ANON {
369             let prof_timer = self.prof.query_provider(Q::NAME);
370
371             let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
372                 self.start_query(job.job.clone(), diagnostics, |tcx| {
373                     tcx.dep_graph.with_anon_task(Q::dep_kind(), || Q::compute(tcx, key))
374                 })
375             });
376
377             drop(prof_timer);
378
379             self.dep_graph.read_index(dep_node_index);
380
381             if unlikely!(!diagnostics.is_empty()) {
382                 self.queries
383                     .on_disk_cache
384                     .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
385             }
386
387             job.complete(&result, dep_node_index);
388
389             return result;
390         }
391
392         let dep_node = Q::to_dep_node(self, &key);
393
394         if !Q::EVAL_ALWAYS {
395             // The diagnostics for this query will be
396             // promoted to the current session during
397             // `try_mark_green()`, so we can ignore them here.
398             let loaded = self.start_query(job.job.clone(), None, |tcx| {
399                 let marked = tcx.dep_graph.try_mark_green_and_read(tcx, &dep_node);
400                 marked.map(|(prev_dep_node_index, dep_node_index)| {
401                     (
402                         tcx.load_from_disk_and_cache_in_memory::<Q>(
403                             key.clone(),
404                             prev_dep_node_index,
405                             dep_node_index,
406                             &dep_node,
407                         ),
408                         dep_node_index,
409                     )
410                 })
411             });
412             if let Some((result, dep_node_index)) = loaded {
413                 job.complete(&result, dep_node_index);
414                 return result;
415             }
416         }
417
418         let (result, dep_node_index) = self.force_query_with_job::<Q>(key, job, dep_node);
419         self.dep_graph.read_index(dep_node_index);
420         result
421     }
422
423     fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'tcx>>(
424         self,
425         key: Q::Key,
426         prev_dep_node_index: SerializedDepNodeIndex,
427         dep_node_index: DepNodeIndex,
428         dep_node: &DepNode,
429     ) -> Q::Value {
430         // Note this function can be called concurrently from the same query
431         // We must ensure that this is handled correctly.
432
433         debug_assert!(self.dep_graph.is_green(dep_node));
434
435         // First we try to load the result from the on-disk cache.
436         let result = if Q::cache_on_disk(self, key.clone(), None)
437             && self.sess.opts.debugging_opts.incremental_queries
438         {
439             let _prof_timer = self.prof.incr_cache_loading(Q::NAME);
440             let result = Q::try_load_from_disk(self, prev_dep_node_index);
441
442             // We always expect to find a cached result for things that
443             // can be forced from `DepNode`.
444             debug_assert!(
445                 !dep_node.kind.can_reconstruct_query_key() || result.is_some(),
446                 "missing on-disk cache entry for {:?}",
447                 dep_node
448             );
449             result
450         } else {
451             // Some things are never cached on disk.
452             None
453         };
454
455         let result = if let Some(result) = result {
456             result
457         } else {
458             // We could not load a result from the on-disk cache, so
459             // recompute.
460             let _prof_timer = self.prof.query_provider(Q::NAME);
461
462             // The dep-graph for this computation is already in-place.
463             let result = self.dep_graph.with_ignore(|| Q::compute(self, key));
464
465             result
466         };
467
468         // If `-Zincremental-verify-ich` is specified, re-hash results from
469         // the cache and make sure that they have the expected fingerprint.
470         if unlikely!(self.sess.opts.debugging_opts.incremental_verify_ich) {
471             self.incremental_verify_ich::<Q>(&result, dep_node, dep_node_index);
472         }
473
474         result
475     }
476
477     #[inline(never)]
478     #[cold]
479     fn incremental_verify_ich<Q: QueryDescription<'tcx>>(
480         self,
481         result: &Q::Value,
482         dep_node: &DepNode,
483         dep_node_index: DepNodeIndex,
484     ) {
485         use crate::ich::Fingerprint;
486
487         assert!(
488             Some(self.dep_graph.fingerprint_of(dep_node_index))
489                 == self.dep_graph.prev_fingerprint_of(dep_node),
490             "fingerprint for green query instance not loaded from cache: {:?}",
491             dep_node,
492         );
493
494         debug!("BEGIN verify_ich({:?})", dep_node);
495         let mut hcx = self.create_stable_hashing_context();
496
497         let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
498         debug!("END verify_ich({:?})", dep_node);
499
500         let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
501
502         assert!(new_hash == old_hash, "found unstable fingerprints for {:?}", dep_node,);
503     }
504
505     #[inline(always)]
506     fn force_query_with_job<Q: QueryDescription<'tcx>>(
507         self,
508         key: Q::Key,
509         job: JobOwner<'_, 'tcx, Q>,
510         dep_node: DepNode,
511     ) -> (Q::Value, DepNodeIndex) {
512         // If the following assertion triggers, it can have two reasons:
513         // 1. Something is wrong with DepNode creation, either here or
514         //    in `DepGraph::try_mark_green()`.
515         // 2. Two distinct query keys get mapped to the same `DepNode`
516         //    (see for example #48923).
517         assert!(
518             !self.dep_graph.dep_node_exists(&dep_node),
519             "forcing query with already existing `DepNode`\n\
520                  - query-key: {:?}\n\
521                  - dep-node: {:?}",
522             key,
523             dep_node
524         );
525
526         let prof_timer = self.prof.query_provider(Q::NAME);
527
528         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
529             self.start_query(job.job.clone(), diagnostics, |tcx| {
530                 if Q::EVAL_ALWAYS {
531                     tcx.dep_graph.with_eval_always_task(
532                         dep_node,
533                         tcx,
534                         key,
535                         Q::compute,
536                         Q::hash_result,
537                     )
538                 } else {
539                     tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, Q::hash_result)
540                 }
541             })
542         });
543
544         drop(prof_timer);
545
546         if unlikely!(!diagnostics.is_empty()) {
547             if dep_node.kind != crate::dep_graph::DepKind::Null {
548                 self.queries.on_disk_cache.store_diagnostics(dep_node_index, diagnostics);
549             }
550         }
551
552         job.complete(&result, dep_node_index);
553
554         (result, dep_node_index)
555     }
556
557     /// Ensure that either this query has all green inputs or been executed.
558     /// Executing `query::ensure(D)` is considered a read of the dep-node `D`.
559     ///
560     /// This function is particularly useful when executing passes for their
561     /// side-effects -- e.g., in order to report errors for erroneous programs.
562     ///
563     /// Note: The optimization is only available during incr. comp.
564     pub(super) fn ensure_query<Q: QueryDescription<'tcx>>(self, key: Q::Key) -> () {
565         if Q::EVAL_ALWAYS {
566             let _ = self.get_query::<Q>(DUMMY_SP, key);
567             return;
568         }
569
570         // Ensuring an anonymous query makes no sense
571         assert!(!Q::ANON);
572
573         let dep_node = Q::to_dep_node(self, &key);
574
575         if self.dep_graph.try_mark_green_and_read(self, &dep_node).is_none() {
576             // A None return from `try_mark_green_and_read` means that this is either
577             // a new dep node or that the dep node has already been marked red.
578             // Either way, we can't call `dep_graph.read()` as we don't have the
579             // DepNodeIndex. We must invoke the query itself. The performance cost
580             // this introduces should be negligible as we'll immediately hit the
581             // in-memory cache, or another query down the line will.
582
583             let _ = self.get_query::<Q>(DUMMY_SP, key);
584         } else {
585             self.prof.query_cache_hit(Q::NAME);
586         }
587     }
588
589     #[allow(dead_code)]
590     fn force_query<Q: QueryDescription<'tcx>>(self, key: Q::Key, span: Span, dep_node: DepNode) {
591         // We may be concurrently trying both execute and force a query.
592         // Ensure that only one of them runs the query.
593         let job = match JobOwner::try_get(self, span, &key) {
594             TryGetJob::NotYetStarted(job) => job,
595             TryGetJob::Cycle(_) | TryGetJob::JobCompleted(_) => return,
596         };
597         self.force_query_with_job::<Q>(key, job, dep_node);
598     }
599 }
600
601 macro_rules! handle_cycle_error {
602     ([][$tcx: expr, $error:expr]) => {{
603         $tcx.report_cycle($error).emit();
604         Value::from_cycle_error($tcx)
605     }};
606     ([fatal_cycle$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
607         $tcx.report_cycle($error).emit();
608         $tcx.sess.abort_if_errors();
609         unreachable!()
610     }};
611     ([cycle_delay_bug$(, $modifiers:ident)*][$tcx:expr, $error:expr]) => {{
612         $tcx.report_cycle($error).delay_as_bug();
613         Value::from_cycle_error($tcx)
614     }};
615     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
616         handle_cycle_error!([$($modifiers),*][$($args)*])
617     };
618 }
619
620 macro_rules! is_anon {
621     ([]) => {{
622         false
623     }};
624     ([anon$(, $modifiers:ident)*]) => {{
625         true
626     }};
627     ([$other:ident$(, $modifiers:ident)*]) => {
628         is_anon!([$($modifiers),*])
629     };
630 }
631
632 macro_rules! is_eval_always {
633     ([]) => {{
634         false
635     }};
636     ([eval_always$(, $modifiers:ident)*]) => {{
637         true
638     }};
639     ([$other:ident$(, $modifiers:ident)*]) => {
640         is_eval_always!([$($modifiers),*])
641     };
642 }
643
644 macro_rules! hash_result {
645     ([][$hcx:expr, $result:expr]) => {{
646         dep_graph::hash_result($hcx, &$result)
647     }};
648     ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
649         None
650     }};
651     ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
652         hash_result!([$($modifiers),*][$($args)*])
653     };
654 }
655
656 macro_rules! define_queries {
657     (<$tcx:tt> $($category:tt {
658         $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
659     },)*) => {
660         define_queries_inner! { <$tcx>
661             $($( $(#[$attr])* category<$category> [$($modifiers)*] fn $name: $node($K) -> $V,)*)*
662         }
663     }
664 }
665
666 macro_rules! define_queries_inner {
667     (<$tcx:tt>
668      $($(#[$attr:meta])* category<$category:tt>
669         [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
670
671         use std::mem;
672         use rustc_data_structures::sharded::Sharded;
673         use crate::{
674             rustc_data_structures::stable_hasher::HashStable,
675             rustc_data_structures::stable_hasher::StableHasher,
676             ich::StableHashingContext
677         };
678         use rustc_data_structures::profiling::ProfileCategory;
679
680         define_queries_struct! {
681             tcx: $tcx,
682             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
683         }
684
685         impl<$tcx> Queries<$tcx> {
686             pub fn new(
687                 providers: IndexVec<CrateNum, Providers<$tcx>>,
688                 fallback_extern_providers: Providers<$tcx>,
689                 on_disk_cache: OnDiskCache<'tcx>,
690             ) -> Self {
691                 Queries {
692                     providers,
693                     fallback_extern_providers: Box::new(fallback_extern_providers),
694                     on_disk_cache,
695                     $($name: Default::default()),*
696                 }
697             }
698
699             #[cfg(parallel_compiler)]
700             pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
701                 let mut jobs = Vec::new();
702
703                 // We use try_lock_shards here since we are only called from the
704                 // deadlock handler, and this shouldn't be locked.
705                 $(
706                     let shards = self.$name.try_lock_shards().unwrap();
707                     jobs.extend(shards.iter().flat_map(|shard| shard.active.values().filter_map(|v|
708                         if let QueryResult::Started(ref job) = *v {
709                             Some(job.clone())
710                         } else {
711                             None
712                         }
713                     )));
714                 )*
715
716                 jobs
717             }
718
719             pub fn print_stats(&self) {
720                 let mut queries = Vec::new();
721
722                 #[derive(Clone)]
723                 struct QueryStats {
724                     name: &'static str,
725                     cache_hits: usize,
726                     key_size: usize,
727                     key_type: &'static str,
728                     value_size: usize,
729                     value_type: &'static str,
730                     entry_count: usize,
731                 }
732
733                 fn stats<'tcx, Q: QueryConfig<'tcx>>(
734                     name: &'static str,
735                     map: &Sharded<QueryCache<'tcx, Q>>,
736                 ) -> QueryStats {
737                     let map = map.lock_shards();
738                     QueryStats {
739                         name,
740                         #[cfg(debug_assertions)]
741                         cache_hits: map.iter().map(|shard| shard.cache_hits).sum(),
742                         #[cfg(not(debug_assertions))]
743                         cache_hits: 0,
744                         key_size: mem::size_of::<Q::Key>(),
745                         key_type: type_name::<Q::Key>(),
746                         value_size: mem::size_of::<Q::Value>(),
747                         value_type: type_name::<Q::Value>(),
748                         entry_count: map.iter().map(|shard| shard.results.len()).sum(),
749                     }
750                 }
751
752                 $(
753                     queries.push(stats::<queries::$name<'_>>(
754                         stringify!($name),
755                         &self.$name,
756                     ));
757                 )*
758
759                 if cfg!(debug_assertions) {
760                     let hits: usize = queries.iter().map(|s| s.cache_hits).sum();
761                     let results: usize = queries.iter().map(|s| s.entry_count).sum();
762                     println!("\nQuery cache hit rate: {}", hits as f64 / (hits + results) as f64);
763                 }
764
765                 let mut query_key_sizes = queries.clone();
766                 query_key_sizes.sort_by_key(|q| q.key_size);
767                 println!("\nLarge query keys:");
768                 for q in query_key_sizes.iter().rev()
769                                         .filter(|q| q.key_size > 8) {
770                     println!(
771                         "   {} - {} x {} - {}",
772                         q.name,
773                         q.key_size,
774                         q.entry_count,
775                         q.key_type
776                     );
777                 }
778
779                 let mut query_value_sizes = queries.clone();
780                 query_value_sizes.sort_by_key(|q| q.value_size);
781                 println!("\nLarge query values:");
782                 for q in query_value_sizes.iter().rev()
783                                           .filter(|q| q.value_size > 8) {
784                     println!(
785                         "   {} - {} x {} - {}",
786                         q.name,
787                         q.value_size,
788                         q.entry_count,
789                         q.value_type
790                     );
791                 }
792
793                 if cfg!(debug_assertions) {
794                     let mut query_cache_hits = queries.clone();
795                     query_cache_hits.sort_by_key(|q| q.cache_hits);
796                     println!("\nQuery cache hits:");
797                     for q in query_cache_hits.iter().rev() {
798                         println!(
799                             "   {} - {} ({}%)",
800                             q.name,
801                             q.cache_hits,
802                             q.cache_hits as f64 / (q.cache_hits + q.entry_count) as f64
803                         );
804                     }
805                 }
806
807                 let mut query_value_count = queries.clone();
808                 query_value_count.sort_by_key(|q| q.entry_count);
809                 println!("\nQuery value count:");
810                 for q in query_value_count.iter().rev() {
811                     println!("   {} - {}", q.name, q.entry_count);
812                 }
813             }
814         }
815
816         #[allow(nonstandard_style)]
817         #[derive(Clone, Copy)]
818         pub enum QueryName {
819             $($name),*
820         }
821
822         impl rustc_data_structures::profiling::QueryName for QueryName {
823             fn discriminant(self) -> std::mem::Discriminant<QueryName> {
824                 std::mem::discriminant(&self)
825             }
826
827             fn as_str(self) -> &'static str {
828                 QueryName::as_str(&self)
829             }
830         }
831
832         impl QueryName {
833             pub fn register_with_profiler(
834                 profiler: &rustc_data_structures::profiling::SelfProfiler,
835             ) {
836                 $(profiler.register_query_name(QueryName::$name);)*
837             }
838
839             pub fn as_str(&self) -> &'static str {
840                 match self {
841                     $(QueryName::$name => stringify!($name),)*
842                 }
843             }
844         }
845
846         #[allow(nonstandard_style)]
847         #[derive(Clone, Debug)]
848         pub enum Query<$tcx> {
849             $($(#[$attr])* $name($K)),*
850         }
851
852         impl<$tcx> Query<$tcx> {
853             pub fn name(&self) -> &'static str {
854                 match *self {
855                     $(Query::$name(_) => stringify!($name),)*
856                 }
857             }
858
859             pub fn describe(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
860                 let (r, name) = match *self {
861                     $(Query::$name(key) => {
862                         (queries::$name::describe(tcx, key), stringify!($name))
863                     })*
864                 };
865                 if tcx.sess.verbose() {
866                     format!("{} [{}]", r, name).into()
867                 } else {
868                     r
869                 }
870             }
871
872             // FIXME(eddyb) Get more valid `Span`s on queries.
873             pub fn default_span(&self, tcx: TyCtxt<$tcx>, span: Span) -> Span {
874                 if !span.is_dummy() {
875                     return span;
876                 }
877                 // The `def_span` query is used to calculate `default_span`,
878                 // so exit to avoid infinite recursion.
879                 if let Query::def_span(..) = *self {
880                     return span
881                 }
882                 match *self {
883                     $(Query::$name(key) => key.default_span(tcx),)*
884                 }
885             }
886
887             pub fn query_name(&self) -> QueryName {
888                 match self {
889                     $(Query::$name(_) => QueryName::$name,)*
890                 }
891             }
892         }
893
894         impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
895             fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
896                 mem::discriminant(self).hash_stable(hcx, hasher);
897                 match *self {
898                     $(Query::$name(key) => key.hash_stable(hcx, hasher),)*
899                 }
900             }
901         }
902
903         pub mod queries {
904             use std::marker::PhantomData;
905
906             $(#[allow(nonstandard_style)]
907             pub struct $name<$tcx> {
908                 data: PhantomData<&$tcx ()>
909             })*
910         }
911
912         // This module and the functions in it exist only to provide a
913         // predictable symbol name prefix for query providers. This is helpful
914         // for analyzing queries in profilers.
915         pub(super) mod __query_compute {
916             $(#[inline(never)]
917             pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
918                 f()
919             })*
920         }
921
922         $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
923             type Key = $K;
924             type Value = $V;
925
926             const NAME: QueryName = QueryName::$name;
927             const CATEGORY: ProfileCategory = $category;
928         }
929
930         impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
931             const ANON: bool = is_anon!([$($modifiers)*]);
932             const EVAL_ALWAYS: bool = is_eval_always!([$($modifiers)*]);
933
934             #[inline(always)]
935             fn query(key: Self::Key) -> Query<'tcx> {
936                 Query::$name(key)
937             }
938
939             #[inline(always)]
940             fn query_cache<'a>(tcx: TyCtxt<$tcx>) -> &'a Sharded<QueryCache<$tcx, Self>> {
941                 &tcx.queries.$name
942             }
943
944             #[allow(unused)]
945             #[inline(always)]
946             fn to_dep_node(tcx: TyCtxt<$tcx>, key: &Self::Key) -> DepNode {
947                 use crate::dep_graph::DepConstructor::*;
948
949                 DepNode::new(tcx, $node(*key))
950             }
951
952             #[inline(always)]
953             fn dep_kind() -> dep_graph::DepKind {
954                 dep_graph::DepKind::$node
955             }
956
957             #[inline]
958             fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value {
959                 __query_compute::$name(move || {
960                     let provider = tcx.queries.providers.get(key.query_crate())
961                         // HACK(eddyb) it's possible crates may be loaded after
962                         // the query engine is created, and because crate loading
963                         // is not yet integrated with the query engine, such crates
964                         // would be missing appropriate entries in `providers`.
965                         .unwrap_or(&tcx.queries.fallback_extern_providers)
966                         .$name;
967                     provider(tcx, key)
968                 })
969             }
970
971             fn hash_result(
972                 _hcx: &mut StableHashingContext<'_>,
973                 _result: &Self::Value
974             ) -> Option<Fingerprint> {
975                 hash_result!([$($modifiers)*][_hcx, _result])
976             }
977
978             fn handle_cycle_error(
979                 tcx: TyCtxt<'tcx>,
980                 error: CycleError<'tcx>
981             ) -> Self::Value {
982                 handle_cycle_error!([$($modifiers)*][tcx, error])
983             }
984         })*
985
986         #[derive(Copy, Clone)]
987         pub struct TyCtxtEnsure<'tcx> {
988             pub tcx: TyCtxt<'tcx>,
989         }
990
991         impl TyCtxtEnsure<$tcx> {
992             $($(#[$attr])*
993             #[inline(always)]
994             pub fn $name(self, key: $K) {
995                 self.tcx.ensure_query::<queries::$name<'_>>(key)
996             })*
997         }
998
999         #[derive(Copy, Clone)]
1000         pub struct TyCtxtAt<'tcx> {
1001             pub tcx: TyCtxt<'tcx>,
1002             pub span: Span,
1003         }
1004
1005         impl Deref for TyCtxtAt<'tcx> {
1006             type Target = TyCtxt<'tcx>;
1007             #[inline(always)]
1008             fn deref(&self) -> &Self::Target {
1009                 &self.tcx
1010             }
1011         }
1012
1013         impl TyCtxt<$tcx> {
1014             /// Returns a transparent wrapper for `TyCtxt`, which ensures queries
1015             /// are executed instead of just returing their results.
1016             #[inline(always)]
1017             pub fn ensure(self) -> TyCtxtEnsure<$tcx> {
1018                 TyCtxtEnsure {
1019                     tcx: self,
1020                 }
1021             }
1022
1023             /// Returns a transparent wrapper for `TyCtxt` which uses
1024             /// `span` as the location of queries performed through it.
1025             #[inline(always)]
1026             pub fn at(self, span: Span) -> TyCtxtAt<$tcx> {
1027                 TyCtxtAt {
1028                     tcx: self,
1029                     span
1030                 }
1031             }
1032
1033             $($(#[$attr])*
1034             #[inline(always)]
1035             pub fn $name(self, key: $K) -> $V {
1036                 self.at(DUMMY_SP).$name(key)
1037             })*
1038         }
1039
1040         impl TyCtxtAt<$tcx> {
1041             $($(#[$attr])*
1042             #[inline(always)]
1043             pub fn $name(self, key: $K) -> $V {
1044                 self.tcx.get_query::<queries::$name<'_>>(self.span, key)
1045             })*
1046         }
1047
1048         define_provider_struct! {
1049             tcx: $tcx,
1050             input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
1051         }
1052
1053         impl<$tcx> Copy for Providers<$tcx> {}
1054         impl<$tcx> Clone for Providers<$tcx> {
1055             fn clone(&self) -> Self { *self }
1056         }
1057     }
1058 }
1059
1060 macro_rules! define_queries_struct {
1061     (tcx: $tcx:tt,
1062      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
1063         pub struct Queries<$tcx> {
1064             /// This provides access to the incrimental comilation on-disk cache for query results.
1065             /// Do not access this directly. It is only meant to be used by
1066             /// `DepGraph::try_mark_green()` and the query infrastructure.
1067             pub(crate) on_disk_cache: OnDiskCache<'tcx>,
1068
1069             providers: IndexVec<CrateNum, Providers<$tcx>>,
1070             fallback_extern_providers: Box<Providers<$tcx>>,
1071
1072             $($(#[$attr])*  $name: Sharded<QueryCache<$tcx, queries::$name<$tcx>>>,)*
1073         }
1074     };
1075 }
1076
1077 macro_rules! define_provider_struct {
1078     (tcx: $tcx:tt,
1079      input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
1080         pub struct Providers<$tcx> {
1081             $(pub $name: fn(TyCtxt<$tcx>, $K) -> $R,)*
1082         }
1083
1084         impl<$tcx> Default for Providers<$tcx> {
1085             fn default() -> Self {
1086                 $(fn $name<$tcx>(_: TyCtxt<$tcx>, key: $K) -> $R {
1087                     bug!("`tcx.{}({:?})` unsupported by its crate",
1088                          stringify!($name), key);
1089                 })*
1090                 Providers { $($name),* }
1091             }
1092         }
1093     };
1094 }
1095
1096 /// The red/green evaluation system will try to mark a specific DepNode in the
1097 /// dependency graph as green by recursively trying to mark the dependencies of
1098 /// that `DepNode` as green. While doing so, it will sometimes encounter a `DepNode`
1099 /// where we don't know if it is red or green and we therefore actually have
1100 /// to recompute its value in order to find out. Since the only piece of
1101 /// information that we have at that point is the `DepNode` we are trying to
1102 /// re-evaluate, we need some way to re-run a query from just that. This is what
1103 /// `force_from_dep_node()` implements.
1104 ///
1105 /// In the general case, a `DepNode` consists of a `DepKind` and an opaque
1106 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
1107 /// is usually constructed by computing a stable hash of the query-key that the
1108 /// `DepNode` corresponds to. Consequently, it is not in general possible to go
1109 /// back from hash to query-key (since hash functions are not reversible). For
1110 /// this reason `force_from_dep_node()` is expected to fail from time to time
1111 /// because we just cannot find out, from the `DepNode` alone, what the
1112 /// corresponding query-key is and therefore cannot re-run the query.
1113 ///
1114 /// The system deals with this case letting `try_mark_green` fail which forces
1115 /// the root query to be re-evaluated.
1116 ///
1117 /// Now, if `force_from_dep_node()` would always fail, it would be pretty useless.
1118 /// Fortunately, we can use some contextual information that will allow us to
1119 /// reconstruct query-keys for certain kinds of `DepNode`s. In particular, we
1120 /// enforce by construction that the GUID/fingerprint of certain `DepNode`s is a
1121 /// valid `DefPathHash`. Since we also always build a huge table that maps every
1122 /// `DefPathHash` in the current codebase to the corresponding `DefId`, we have
1123 /// everything we need to re-run the query.
1124 ///
1125 /// Take the `mir_validated` query as an example. Like many other queries, it
1126 /// just has a single parameter: the `DefId` of the item it will compute the
1127 /// validated MIR for. Now, when we call `force_from_dep_node()` on a `DepNode`
1128 /// with kind `MirValidated`, we know that the GUID/fingerprint of the `DepNode`
1129 /// is actually a `DefPathHash`, and can therefore just look up the corresponding
1130 /// `DefId` in `tcx.def_path_hash_to_def_id`.
1131 ///
1132 /// When you implement a new query, it will likely have a corresponding new
1133 /// `DepKind`, and you'll have to support it here in `force_from_dep_node()`. As
1134 /// a rule of thumb, if your query takes a `DefId` or `DefIndex` as sole parameter,
1135 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
1136 /// add it to the "We don't have enough information to reconstruct..." group in
1137 /// the match below.
1138 pub fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: &DepNode) -> bool {
1139     use crate::dep_graph::RecoverKey;
1140
1141     // We must avoid ever having to call `force_from_dep_node()` for a
1142     // `DepNode::codegen_unit`:
1143     // Since we cannot reconstruct the query key of a `DepNode::codegen_unit`, we
1144     // would always end up having to evaluate the first caller of the
1145     // `codegen_unit` query that *is* reconstructible. This might very well be
1146     // the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
1147     // to re-trigger calling the `codegen_unit` query with the right key. At
1148     // that point we would already have re-done all the work we are trying to
1149     // avoid doing in the first place.
1150     // The solution is simple: Just explicitly call the `codegen_unit` query for
1151     // each CGU, right after partitioning. This way `try_mark_green` will always
1152     // hit the cache instead of having to go through `force_from_dep_node`.
1153     // This assertion makes sure, we actually keep applying the solution above.
1154     debug_assert!(
1155         dep_node.kind != DepKind::codegen_unit,
1156         "calling force_from_dep_node() on DepKind::codegen_unit"
1157     );
1158
1159     if !dep_node.kind.can_reconstruct_query_key() {
1160         return false;
1161     }
1162
1163     rustc_dep_node_force!([dep_node, tcx]
1164         // These are inputs that are expected to be pre-allocated and that
1165         // should therefore always be red or green already.
1166         DepKind::AllLocalTraitImpls |
1167         DepKind::Krate |
1168         DepKind::CrateMetadata |
1169         DepKind::HirBody |
1170         DepKind::Hir |
1171
1172         // These are anonymous nodes.
1173         DepKind::TraitSelect |
1174
1175         // We don't have enough information to reconstruct the query key of
1176         // these.
1177         DepKind::CompileCodegenUnit => {
1178             bug!("force_from_dep_node: encountered {:?}", dep_node)
1179         }
1180
1181         DepKind::Analysis => {
1182             let def_id = if let Some(def_id) = dep_node.extract_def_id(tcx) {
1183                 def_id
1184             } else {
1185                 // Return from the whole function.
1186                 return false
1187             };
1188             tcx.force_query::<crate::ty::query::queries::analysis<'_>>(
1189                 def_id.krate,
1190                 DUMMY_SP,
1191                 *dep_node
1192             );
1193         }
1194     );
1195
1196     true
1197 }