1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The implementation of the query system itself. Defines the macros
12 //! that generate the actual methods on tcx which find and execute the
13 //! provider, manage the caches, and so forth.
15 use dep_graph::{DepNodeIndex, DepNode, DepKind, DepNodeColor};
16 use errors::DiagnosticBuilder;
18 use errors::Diagnostic;
19 use errors::FatalError;
23 use ty::maps::config::QueryConfig;
24 use ty::maps::config::QueryDescription;
25 use ty::maps::job::{QueryJob, QueryResult, QueryInfo};
28 use util::common::{profq_msg, ProfileQueriesMsg, QueryMsg};
30 use rustc_data_structures::fx::{FxHashMap};
31 use rustc_data_structures::sync::{Lrc, Lock};
34 use std::collections::hash_map::Entry;
36 use syntax::codemap::DUMMY_SP;
38 pub struct QueryMap<'tcx, D: QueryConfig<'tcx> + ?Sized> {
39 pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
40 pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
43 pub(super) struct QueryValue<T> {
45 pub(super) index: DepNodeIndex,
48 impl<T> QueryValue<T> {
49 pub(super) fn new(value: T,
50 dep_node_index: DepNodeIndex)
54 index: dep_node_index,
59 impl<'tcx, M: QueryConfig<'tcx>> QueryMap<'tcx, M> {
60 pub(super) fn new() -> QueryMap<'tcx, M> {
68 // If enabled, send a message to the profile-queries thread
69 macro_rules! profq_msg {
70 ($tcx:expr, $msg:expr) => {
71 if cfg!(debug_assertions) {
72 if $tcx.sess.profile_queries() {
73 profq_msg($tcx.sess, $msg)
79 // If enabled, format a key using its debug string, which can be
80 // expensive to compute (in terms of time).
81 macro_rules! profq_query_msg {
82 ($query:expr, $tcx:expr, $key:expr) => {{
83 let msg = if cfg!(debug_assertions) {
84 if $tcx.sess.profile_queries_and_keys() {
85 Some(format!("{:?}", $key))
95 /// A type representing the responsibility to execute the job in the `job` field.
96 /// This will poison the relevant query if dropped.
97 pub(super) struct JobOwner<'a, 'tcx: 'a, Q: QueryDescription<'tcx> + 'a> {
98 map: &'a Lock<QueryMap<'tcx, Q>>,
100 job: Lrc<QueryJob<'tcx>>,
103 impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
104 /// Either gets a JobOwner corresponding the the query, allowing us to
105 /// start executing the query, or it returns with the result of the query.
106 /// If the query is executing elsewhere, this will wait for it.
107 /// If the query panicked, this will silently panic.
108 pub(super) fn try_get(
109 tcx: TyCtxt<'a, 'tcx, '_>,
112 ) -> TryGetJob<'a, 'tcx, Q> {
113 let map = Q::query_map(tcx);
115 let mut lock = map.borrow_mut();
116 if let Some(value) = lock.results.get(key) {
117 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
118 let result = Ok((value.value.clone(), value.index));
119 return TryGetJob::JobCompleted(result);
121 let job = match lock.active.entry((*key).clone()) {
122 Entry::Occupied(entry) => {
124 QueryResult::Started(ref job) => job.clone(),
125 QueryResult::Poisoned => FatalError.raise(),
128 Entry::Vacant(entry) => {
129 // No job entry for this query. Return a new one to be started later
130 return tls::with_related_context(tcx, |icx| {
131 let info = QueryInfo {
133 query: Q::query(key.clone()),
135 let job = Lrc::new(QueryJob::new(info, icx.query.clone()));
136 let owner = JobOwner {
141 entry.insert(QueryResult::Started(job));
142 TryGetJob::NotYetStarted(owner)
148 if let Err(cycle) = job.await(tcx, span) {
149 return TryGetJob::JobCompleted(Err(cycle));
154 /// Completes the query by updating the query map with the `result`,
155 /// signals the waiter and forgets the JobOwner, so it won't poison the query
156 pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
157 // We can move out of `self` here because we `mem::forget` it below
158 let key = unsafe { ptr::read(&self.key) };
159 let job = unsafe { ptr::read(&self.job) };
162 // Forget ourself so our destructor won't poison the query
165 let value = QueryValue::new(result.clone(), dep_node_index);
167 let mut lock = map.borrow_mut();
168 lock.active.remove(&key);
169 lock.results.insert(key, value);
172 job.signal_complete();
175 /// Executes a job by changing the ImplicitCtxt to point to the
176 /// new query job while it executes. It returns the diagnostics
177 /// captured during execution and the actual result.
178 pub(super) fn start<'lcx, F, R>(
180 tcx: TyCtxt<'_, 'tcx, 'lcx>,
182 -> (R, Vec<Diagnostic>)
184 F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'lcx>) -> R
186 // The TyCtxt stored in TLS has the same global interner lifetime
187 // as `tcx`, so we use `with_related_context` to relate the 'gcx lifetimes
188 // when accessing the ImplicitCtxt
189 let r = tls::with_related_context(tcx, move |current_icx| {
190 // Update the ImplicitCtxt to point to our new query job
191 let new_icx = tls::ImplicitCtxt {
193 query: Some(self.job.clone()),
194 layout_depth: current_icx.layout_depth,
195 task: current_icx.task,
198 // Use the ImplicitCtxt while we execute the query
199 tls::enter_context(&new_icx, |_| {
204 // Extract the diagnostic from the job
205 let diagnostics = mem::replace(&mut *self.job.diagnostics.lock(), Vec::new());
211 impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
213 // Poison the query so jobs waiting on it panic
214 self.map.borrow_mut().active.insert(self.key.clone(), QueryResult::Poisoned);
215 // Also signal the completion of the job, so waiters
216 // will continue execution
217 self.job.signal_complete();
222 pub(super) struct CycleError<'tcx> {
223 /// The query and related span which uses the cycle
224 pub(super) usage: Option<(Span, Query<'tcx>)>,
225 pub(super) cycle: Vec<QueryInfo<'tcx>>,
228 /// The result of `try_get_lock`
229 pub(super) enum TryGetJob<'a, 'tcx: 'a, D: QueryDescription<'tcx> + 'a> {
230 /// The query is not yet started. Contains a guard to the map eventually used to start it.
231 NotYetStarted(JobOwner<'a, 'tcx, D>),
233 /// The query was already completed.
234 /// Returns the result of the query and its dep node index
235 /// if it succeeded or a cycle error if it failed
236 JobCompleted(Result<(D::Value, DepNodeIndex), CycleError<'tcx>>),
239 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
240 pub(super) fn report_cycle(self, CycleError { usage, cycle: stack }: CycleError<'gcx>)
241 -> DiagnosticBuilder<'a>
243 assert!(!stack.is_empty());
245 let fix_span = |span: Span, query: &Query<'gcx>| {
246 self.sess.codemap().def_span(query.default_span(self, span))
249 // Disable naming impls with types in this path, since that
250 // sometimes cycles itself, leading to extra cycle errors.
251 // (And cycle errors around impls tend to occur during the
252 // collect/coherence phases anyhow.)
253 item_path::with_forced_impl_filename_line(|| {
254 let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
255 let mut err = struct_span_err!(self.sess,
258 "cycle detected when {}",
259 stack[0].query.describe(self));
261 for i in 1..stack.len() {
262 let query = &stack[i].query;
263 let span = fix_span(stack[(i + 1) % stack.len()].span, query);
264 err.span_note(span, &format!("...which requires {}...", query.describe(self)));
267 err.note(&format!("...which again requires {}, completing the cycle",
268 stack[0].query.describe(self)));
270 if let Some((span, query)) = usage {
271 err.span_note(fix_span(span, &query),
272 &format!("cycle used when {}", query.describe(self)));
279 pub fn try_print_query_stack() {
280 eprintln!("query stack during panic:");
282 tls::with_context_opt(|icx| {
283 if let Some(icx) = icx {
284 let mut current_query = icx.query.clone();
287 while let Some(query) = current_query {
288 let mut db = DiagnosticBuilder::new(icx.tcx.sess.diagnostic(),
290 &format!("#{} [{}] {}",
292 query.info.query.name(),
293 query.info.query.describe(icx.tcx)));
294 db.set_span(icx.tcx.sess.codemap().def_span(query.info.span));
295 icx.tcx.sess.diagnostic().force_print_db(db);
297 current_query = query.parent.clone();
303 eprintln!("end of query stack");
306 /// Try to read a node index for the node dep_node.
307 /// A node will have an index, when it's already been marked green, or when we can mark it
308 /// green. This function will mark the current task as a reader of the specified node, when
309 /// the a node index can be found for that node.
310 pub(super) fn try_mark_green_and_read(self, dep_node: &DepNode) -> Option<DepNodeIndex> {
311 match self.dep_graph.node_color(dep_node) {
312 Some(DepNodeColor::Green(dep_node_index)) => {
313 self.dep_graph.read_index(dep_node_index);
316 Some(DepNodeColor::Red) => {
320 // try_mark_green (called below) will panic when full incremental
321 // compilation is disabled. If that's the case, we can't try to mark nodes
322 // as green anyway, so we can safely return None here.
323 if !self.dep_graph.is_fully_enabled() {
326 match self.dep_graph.try_mark_green(self.global_tcx(), &dep_node) {
327 Some(dep_node_index) => {
328 debug_assert!(self.dep_graph.is_green(&dep_node));
329 self.dep_graph.read_index(dep_node_index);
340 fn try_get_with<Q: QueryDescription<'gcx>>(
344 -> Result<Q::Value, CycleError<'gcx>>
346 debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
352 ProfileQueriesMsg::QueryBegin(
354 profq_query_msg!(Q::NAME, self, key),
358 let job = match JobOwner::try_get(self, span, &key) {
359 TryGetJob::NotYetStarted(job) => job,
360 TryGetJob::JobCompleted(result) => {
361 return result.map(|(v, index)| {
362 self.dep_graph.read_index(index);
368 // Fast path for when incr. comp. is off. `to_dep_node` is
369 // expensive for some DepKinds.
370 if !self.dep_graph.is_fully_enabled() {
371 let null_dep_node = DepNode::new_no_params(::dep_graph::DepKind::Null);
372 return self.force_query_with_job::<Q>(key, job, null_dep_node).map(|(v, _)| v);
375 let dep_node = Q::to_dep_node(self, &key);
377 if dep_node.kind.is_anon() {
378 profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
380 let res = job.start(self, |tcx| {
381 tcx.dep_graph.with_anon_task(dep_node.kind, || {
382 Q::compute(tcx.global_tcx(), key)
386 profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
387 let ((result, dep_node_index), diagnostics) = res;
389 self.dep_graph.read_index(dep_node_index);
391 self.on_disk_query_result_cache
392 .store_diagnostics_for_anon_node(dep_node_index, diagnostics);
394 job.complete(&result, dep_node_index);
399 if !dep_node.kind.is_input() {
400 if let Some(dep_node_index) = self.try_mark_green_and_read(&dep_node) {
401 profq_msg!(self, ProfileQueriesMsg::CacheHit);
402 return self.load_from_disk_and_cache_in_memory::<Q>(key,
409 match self.force_query_with_job::<Q>(key, job, dep_node) {
410 Ok((result, dep_node_index)) => {
411 self.dep_graph.read_index(dep_node_index);
418 fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'gcx>>(
421 job: JobOwner<'a, 'gcx, Q>,
422 dep_node_index: DepNodeIndex,
424 ) -> Result<Q::Value, CycleError<'gcx>>
426 // Note this function can be called concurrently from the same query
427 // We must ensure that this is handled correctly
429 debug_assert!(self.dep_graph.is_green(dep_node));
431 // First we try to load the result from the on-disk cache
432 let result = if Q::cache_on_disk(key.clone()) &&
433 self.sess.opts.debugging_opts.incremental_queries {
434 let prev_dep_node_index =
435 self.dep_graph.prev_dep_node_index_of(dep_node);
436 let result = Q::try_load_from_disk(self.global_tcx(),
437 prev_dep_node_index);
439 // We always expect to find a cached result for things that
440 // can be forced from DepNode.
441 debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
443 "Missing on-disk cache entry for {:?}",
447 // Some things are never cached on disk.
451 let result = if let Some(result) = result {
454 // We could not load a result from the on-disk cache, so
457 // The diagnostics for this query have already been
458 // promoted to the current session during
459 // try_mark_green(), so we can ignore them here.
460 let (result, _) = job.start(self, |tcx| {
461 // The dep-graph for this computation is already in
463 tcx.dep_graph.with_ignore(|| {
470 // If -Zincremental-verify-ich is specified, re-hash results from
471 // the cache and make sure that they have the expected fingerprint.
472 if self.sess.opts.debugging_opts.incremental_verify_ich {
473 use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
474 use ich::Fingerprint;
476 assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
477 self.dep_graph.prev_fingerprint_of(dep_node),
478 "Fingerprint for green query instance not loaded \
479 from cache: {:?}", dep_node);
481 debug!("BEGIN verify_ich({:?})", dep_node);
482 let mut hcx = self.create_stable_hashing_context();
483 let mut hasher = StableHasher::new();
485 result.hash_stable(&mut hcx, &mut hasher);
487 let new_hash: Fingerprint = hasher.finish();
488 debug!("END verify_ich({:?})", dep_node);
490 let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
492 assert!(new_hash == old_hash, "Found unstable fingerprints \
493 for {:?}", dep_node);
496 if self.sess.opts.debugging_opts.query_dep_graph {
497 self.dep_graph.mark_loaded_from_cache(dep_node_index, true);
500 job.complete(&result, dep_node_index);
505 fn force_query_with_job<Q: QueryDescription<'gcx>>(
508 job: JobOwner<'_, 'gcx, Q>,
510 -> Result<(Q::Value, DepNodeIndex), CycleError<'gcx>> {
511 // If the following assertion triggers, it can have two reasons:
512 // 1. Something is wrong with DepNode creation, either here or
513 // in DepGraph::try_mark_green()
514 // 2. Two distinct query keys get mapped to the same DepNode
515 // (see for example #48923)
516 assert!(!self.dep_graph.dep_node_exists(&dep_node),
517 "Forcing query with already existing DepNode.\n\
522 profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
523 let res = job.start(self, |tcx| {
524 if dep_node.kind.is_eval_always() {
525 tcx.dep_graph.with_eval_always_task(dep_node,
530 tcx.dep_graph.with_task(dep_node,
536 profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
538 let ((result, dep_node_index), diagnostics) = res;
540 if self.sess.opts.debugging_opts.query_dep_graph {
541 self.dep_graph.mark_loaded_from_cache(dep_node_index, false);
544 if dep_node.kind != ::dep_graph::DepKind::Null {
545 self.on_disk_query_result_cache
546 .store_diagnostics(dep_node_index, diagnostics);
549 job.complete(&result, dep_node_index);
551 Ok((result, dep_node_index))
554 /// Ensure that either this query has all green inputs or been executed.
555 /// Executing query::ensure(D) is considered a read of the dep-node D.
557 /// This function is particularly useful when executing passes for their
558 /// side-effects -- e.g., in order to report errors for erroneous programs.
560 /// Note: The optimization is only available during incr. comp.
561 pub fn ensure_query<Q: QueryDescription<'gcx>>(self, key: Q::Key) -> () {
562 let dep_node = Q::to_dep_node(self, &key);
564 // Ensuring an "input" or anonymous query makes no sense
565 assert!(!dep_node.kind.is_anon());
566 assert!(!dep_node.kind.is_input());
567 if self.try_mark_green_and_read(&dep_node).is_none() {
568 // A None return from `try_mark_green_and_read` means that this is either
569 // a new dep node or that the dep node has already been marked red.
570 // Either way, we can't call `dep_graph.read()` as we don't have the
571 // DepNodeIndex. We must invoke the query itself. The performance cost
572 // this introduces should be negligible as we'll immediately hit the
573 // in-memory cache, or another query down the line will.
574 let _ = self.get_query::<Q>(DUMMY_SP, key);
579 fn force_query<Q: QueryDescription<'gcx>>(
584 ) -> Result<(Q::Value, DepNodeIndex), CycleError<'gcx>> {
585 // We may be concurrently trying both execute and force a query
586 // Ensure that only one of them runs the query
587 let job = match JobOwner::try_get(self, span, &key) {
588 TryGetJob::NotYetStarted(job) => job,
589 TryGetJob::JobCompleted(result) => return result,
591 self.force_query_with_job::<Q>(key, job, dep_node)
594 pub fn try_get_query<Q: QueryDescription<'gcx>>(
598 ) -> Result<Q::Value, DiagnosticBuilder<'a>> {
599 match self.try_get_with::<Q>(span, key) {
601 Err(e) => Err(self.report_cycle(e)),
605 pub fn get_query<Q: QueryDescription<'gcx>>(self, span: Span, key: Q::Key) -> Q::Value {
606 self.try_get_query::<Q>(span, key).unwrap_or_else(|mut e| {
608 Q::handle_cycle_error(self)
613 macro_rules! handle_cycle_error {
614 ([][$this: expr]) => {{
615 Value::from_cycle_error($this.global_tcx())
617 ([fatal_cycle$(, $modifiers:ident)*][$this:expr]) => {{
618 $this.sess.abort_if_errors();
621 ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
622 handle_cycle_error!([$($modifiers),*][$($args)*])
626 macro_rules! define_maps {
629 [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
631 use rustc_data_structures::sync::Lock;
635 input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
638 impl<$tcx> Maps<$tcx> {
639 pub fn new(providers: IndexVec<CrateNum, Providers<$tcx>>)
643 $($name: Lock::new(QueryMap::new())),*
649 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
650 pub enum Query<$tcx> {
651 $($(#[$attr])* $name($K)),*
654 impl<$tcx> Query<$tcx> {
655 pub fn name(&self) -> &'static str {
657 $(Query::$name(_) => stringify!($name),)*
661 pub fn describe(&self, tcx: TyCtxt) -> String {
662 let (r, name) = match *self {
663 $(Query::$name(key) => {
664 (queries::$name::describe(tcx, key), stringify!($name))
667 if tcx.sess.verbose() {
668 format!("{} [{}]", r, name)
674 // FIXME(eddyb) Get more valid Span's on queries.
675 pub fn default_span(&self, tcx: TyCtxt<'_, $tcx, '_>, span: Span) -> Span {
676 if span != DUMMY_SP {
679 // The def_span query is used to calculate default_span,
680 // so exit to avoid infinite recursion
682 Query::def_span(..) => return span,
686 $(Query::$name(key) => key.default_span(tcx),)*
692 use std::marker::PhantomData;
694 $(#[allow(bad_style)]
695 pub struct $name<$tcx> {
696 data: PhantomData<&$tcx ()>
700 $(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
704 const NAME: &'static str = stringify!($name);
706 fn query(key: Self::Key) -> Query<'tcx> {
710 fn query_map<'a>(tcx: TyCtxt<'a, $tcx, '_>) -> &'a Lock<QueryMap<$tcx, Self>> {
715 fn to_dep_node(tcx: TyCtxt<'_, $tcx, '_>, key: &Self::Key) -> DepNode {
716 use dep_graph::DepConstructor::*;
718 DepNode::new(tcx, $node(*key))
721 fn compute(tcx: TyCtxt<'_, 'tcx, '_>, key: Self::Key) -> Self::Value {
722 let provider = tcx.maps.providers[key.map_crate()].$name;
723 provider(tcx.global_tcx(), key)
726 fn handle_cycle_error(tcx: TyCtxt<'_, 'tcx, '_>) -> Self::Value {
727 handle_cycle_error!([$($modifiers)*][tcx])
731 impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
732 /// Ensure that either this query has all green inputs or been executed.
733 /// Executing query::ensure(D) is considered a read of the dep-node D.
735 /// This function is particularly useful when executing passes for their
736 /// side-effects -- e.g., in order to report errors for erroneous programs.
738 /// Note: The optimization is only available during incr. comp.
739 pub fn ensure(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> () {
740 tcx.ensure_query::<queries::$name>(key);
744 #[derive(Copy, Clone)]
745 pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
746 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
750 impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
751 type Target = TyCtxt<'a, 'gcx, 'tcx>;
752 fn deref(&self) -> &Self::Target {
757 impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
758 /// Return a transparent wrapper for `TyCtxt` which uses
759 /// `span` as the location of queries performed through it.
760 pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
768 pub fn $name(self, key: $K) -> $V {
769 self.at(DUMMY_SP).$name(key)
773 impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
775 pub fn $name(self, key: $K) -> $V {
776 self.tcx.get_query::<queries::$name>(self.span, key)
780 define_provider_struct! {
782 input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
785 impl<$tcx> Copy for Providers<$tcx> {}
786 impl<$tcx> Clone for Providers<$tcx> {
787 fn clone(&self) -> Self { *self }
792 macro_rules! define_map_struct {
794 input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
795 pub struct Maps<$tcx> {
796 providers: IndexVec<CrateNum, Providers<$tcx>>,
797 $($(#[$attr])* $name: Lock<QueryMap<$tcx, queries::$name<$tcx>>>,)*
802 macro_rules! define_provider_struct {
804 input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
805 pub struct Providers<$tcx> {
806 $(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
809 impl<$tcx> Default for Providers<$tcx> {
810 fn default() -> Self {
811 $(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
812 bug!("tcx.maps.{}({:?}) unsupported by its crate",
813 stringify!($name), key);
815 Providers { $($name),* }
822 /// The red/green evaluation system will try to mark a specific DepNode in the
823 /// dependency graph as green by recursively trying to mark the dependencies of
824 /// that DepNode as green. While doing so, it will sometimes encounter a DepNode
825 /// where we don't know if it is red or green and we therefore actually have
826 /// to recompute its value in order to find out. Since the only piece of
827 /// information that we have at that point is the DepNode we are trying to
828 /// re-evaluate, we need some way to re-run a query from just that. This is what
829 /// `force_from_dep_node()` implements.
831 /// In the general case, a DepNode consists of a DepKind and an opaque
832 /// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
833 /// is usually constructed by computing a stable hash of the query-key that the
834 /// DepNode corresponds to. Consequently, it is not in general possible to go
835 /// back from hash to query-key (since hash functions are not reversible). For
836 /// this reason `force_from_dep_node()` is expected to fail from time to time
837 /// because we just cannot find out, from the DepNode alone, what the
838 /// corresponding query-key is and therefore cannot re-run the query.
840 /// The system deals with this case letting `try_mark_green` fail which forces
841 /// the root query to be re-evaluated.
843 /// Now, if force_from_dep_node() would always fail, it would be pretty useless.
844 /// Fortunately, we can use some contextual information that will allow us to
845 /// reconstruct query-keys for certain kinds of DepNodes. In particular, we
846 /// enforce by construction that the GUID/fingerprint of certain DepNodes is a
847 /// valid DefPathHash. Since we also always build a huge table that maps every
848 /// DefPathHash in the current codebase to the corresponding DefId, we have
849 /// everything we need to re-run the query.
851 /// Take the `mir_validated` query as an example. Like many other queries, it
852 /// just has a single parameter: the DefId of the item it will compute the
853 /// validated MIR for. Now, when we call `force_from_dep_node()` on a dep-node
854 /// with kind `MirValidated`, we know that the GUID/fingerprint of the dep-node
855 /// is actually a DefPathHash, and can therefore just look up the corresponding
856 /// DefId in `tcx.def_path_hash_to_def_id`.
858 /// When you implement a new query, it will likely have a corresponding new
859 /// DepKind, and you'll have to support it here in `force_from_dep_node()`. As
860 /// a rule of thumb, if your query takes a DefId or DefIndex as sole parameter,
861 /// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
862 /// add it to the "We don't have enough information to reconstruct..." group in
864 pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>,
867 use hir::def_id::LOCAL_CRATE;
869 // We must avoid ever having to call force_from_dep_node() for a
870 // DepNode::CodegenUnit:
871 // Since we cannot reconstruct the query key of a DepNode::CodegenUnit, we
872 // would always end up having to evaluate the first caller of the
873 // `codegen_unit` query that *is* reconstructible. This might very well be
874 // the `compile_codegen_unit` query, thus re-translating the whole CGU just
875 // to re-trigger calling the `codegen_unit` query with the right key. At
876 // that point we would already have re-done all the work we are trying to
877 // avoid doing in the first place.
878 // The solution is simple: Just explicitly call the `codegen_unit` query for
879 // each CGU, right after partitioning. This way `try_mark_green` will always
880 // hit the cache instead of having to go through `force_from_dep_node`.
881 // This assertion makes sure, we actually keep applying the solution above.
882 debug_assert!(dep_node.kind != DepKind::CodegenUnit,
883 "calling force_from_dep_node() on DepKind::CodegenUnit");
885 if !dep_node.kind.can_reconstruct_query_key() {
889 macro_rules! def_id {
891 if let Some(def_id) = dep_node.extract_def_id(tcx) {
894 // return from the whole function
901 () => { (def_id!()).krate }
905 ($query:ident, $key:expr) => {
907 use $crate::util::common::{ProfileQueriesMsg, profq_msg};
910 ProfileQueriesMsg::QueryBegin(
912 profq_query_msg!(::ty::maps::queries::$query::NAME, tcx, $key),
916 match tcx.force_query::<::ty::maps::queries::$query>($key, DUMMY_SP, *dep_node) {
919 tcx.report_cycle(e).emit();
926 // FIXME(#45015): We should try move this boilerplate code into a macro
928 match dep_node.kind {
929 // These are inputs that are expected to be pre-allocated and that
930 // should therefore always be red or green already
931 DepKind::AllLocalTraitImpls |
933 DepKind::CrateMetadata |
937 // This are anonymous nodes
938 DepKind::TraitSelect |
940 // We don't have enough information to reconstruct the query key of
948 DepKind::InstanceSymbolName |
950 DepKind::BorrowCheckKrate |
951 DepKind::Specializes |
952 DepKind::ImplementationsOfTrait |
953 DepKind::TypeParamPredicates |
954 DepKind::CodegenUnit |
955 DepKind::CompileCodegenUnit |
956 DepKind::FulfillObligation |
957 DepKind::VtableMethods |
958 DepKind::EraseRegionsTy |
959 DepKind::NormalizeProjectionTy |
960 DepKind::NormalizeTyAfterErasingRegions |
961 DepKind::DropckOutlives |
962 DepKind::EvaluateObligation |
963 DepKind::SubstituteNormalizeAndTestPredicates |
964 DepKind::InstanceDefSizeEstimate |
965 DepKind::ProgramClausesForEnv |
967 // This one should never occur in this context
969 bug!("force_from_dep_node() - Encountered {:?}", dep_node)
972 // These are not queries
973 DepKind::CoherenceCheckTrait |
974 DepKind::ItemVarianceConstraints => {
978 DepKind::RegionScopeTree => { force!(region_scope_tree, def_id!()); }
980 DepKind::Coherence => { force!(crate_inherent_impls, LOCAL_CRATE); }
981 DepKind::CoherenceInherentImplOverlapCheck => {
982 force!(crate_inherent_impls_overlap_check, LOCAL_CRATE)
984 DepKind::PrivacyAccessLevels => { force!(privacy_access_levels, LOCAL_CRATE); }
985 DepKind::MirBuilt => { force!(mir_built, def_id!()); }
986 DepKind::MirConstQualif => { force!(mir_const_qualif, def_id!()); }
987 DepKind::MirConst => { force!(mir_const, def_id!()); }
988 DepKind::MirValidated => { force!(mir_validated, def_id!()); }
989 DepKind::MirOptimized => { force!(optimized_mir, def_id!()); }
991 DepKind::BorrowCheck => { force!(borrowck, def_id!()); }
992 DepKind::MirBorrowCheck => { force!(mir_borrowck, def_id!()); }
993 DepKind::UnsafetyCheckResult => { force!(unsafety_check_result, def_id!()); }
994 DepKind::UnsafeDeriveOnReprPacked => { force!(unsafe_derive_on_repr_packed, def_id!()); }
995 DepKind::Reachability => { force!(reachable_set, LOCAL_CRATE); }
996 DepKind::MirKeys => { force!(mir_keys, LOCAL_CRATE); }
997 DepKind::CrateVariances => { force!(crate_variances, LOCAL_CRATE); }
998 DepKind::AssociatedItems => { force!(associated_item, def_id!()); }
999 DepKind::TypeOfItem => { force!(type_of, def_id!()); }
1000 DepKind::GenericsOfItem => { force!(generics_of, def_id!()); }
1001 DepKind::PredicatesOfItem => { force!(predicates_of, def_id!()); }
1002 DepKind::InferredOutlivesOf => { force!(inferred_outlives_of, def_id!()); }
1003 DepKind::InferredOutlivesCrate => { force!(inferred_outlives_crate, LOCAL_CRATE); }
1004 DepKind::SuperPredicatesOfItem => { force!(super_predicates_of, def_id!()); }
1005 DepKind::TraitDefOfItem => { force!(trait_def, def_id!()); }
1006 DepKind::AdtDefOfItem => { force!(adt_def, def_id!()); }
1007 DepKind::ImplTraitRef => { force!(impl_trait_ref, def_id!()); }
1008 DepKind::ImplPolarity => { force!(impl_polarity, def_id!()); }
1009 DepKind::FnSignature => { force!(fn_sig, def_id!()); }
1010 DepKind::CoerceUnsizedInfo => { force!(coerce_unsized_info, def_id!()); }
1011 DepKind::ItemVariances => { force!(variances_of, def_id!()); }
1012 DepKind::IsConstFn => { force!(is_const_fn, def_id!()); }
1013 DepKind::IsForeignItem => { force!(is_foreign_item, def_id!()); }
1014 DepKind::SizedConstraint => { force!(adt_sized_constraint, def_id!()); }
1015 DepKind::DtorckConstraint => { force!(adt_dtorck_constraint, def_id!()); }
1016 DepKind::AdtDestructor => { force!(adt_destructor, def_id!()); }
1017 DepKind::AssociatedItemDefIds => { force!(associated_item_def_ids, def_id!()); }
1018 DepKind::InherentImpls => { force!(inherent_impls, def_id!()); }
1019 DepKind::TypeckBodiesKrate => { force!(typeck_item_bodies, LOCAL_CRATE); }
1020 DepKind::TypeckTables => { force!(typeck_tables_of, def_id!()); }
1021 DepKind::UsedTraitImports => { force!(used_trait_imports, def_id!()); }
1022 DepKind::HasTypeckTables => { force!(has_typeck_tables, def_id!()); }
1023 DepKind::SymbolName => { force!(def_symbol_name, def_id!()); }
1024 DepKind::SpecializationGraph => { force!(specialization_graph_of, def_id!()); }
1025 DepKind::ObjectSafety => { force!(is_object_safe, def_id!()); }
1026 DepKind::TraitImpls => { force!(trait_impls_of, def_id!()); }
1027 DepKind::CheckMatch => { force!(check_match, def_id!()); }
1029 DepKind::ParamEnv => { force!(param_env, def_id!()); }
1030 DepKind::DescribeDef => { force!(describe_def, def_id!()); }
1031 DepKind::DefSpan => { force!(def_span, def_id!()); }
1032 DepKind::LookupStability => { force!(lookup_stability, def_id!()); }
1033 DepKind::LookupDeprecationEntry => {
1034 force!(lookup_deprecation_entry, def_id!());
1036 DepKind::ConstIsRvaluePromotableToStatic => {
1037 force!(const_is_rvalue_promotable_to_static, def_id!());
1039 DepKind::RvaluePromotableMap => { force!(rvalue_promotable_map, def_id!()); }
1040 DepKind::ImplParent => { force!(impl_parent, def_id!()); }
1041 DepKind::TraitOfItem => { force!(trait_of_item, def_id!()); }
1042 DepKind::IsReachableNonGeneric => { force!(is_reachable_non_generic, def_id!()); }
1043 DepKind::IsUnreachableLocalDefinition => {
1044 force!(is_unreachable_local_definition, def_id!());
1046 DepKind::IsMirAvailable => { force!(is_mir_available, def_id!()); }
1047 DepKind::ItemAttrs => { force!(item_attrs, def_id!()); }
1048 DepKind::TransFnAttrs => { force!(trans_fn_attrs, def_id!()); }
1049 DepKind::FnArgNames => { force!(fn_arg_names, def_id!()); }
1050 DepKind::RenderedConst => { force!(rendered_const, def_id!()); }
1051 DepKind::DylibDepFormats => { force!(dylib_dependency_formats, krate!()); }
1052 DepKind::IsPanicRuntime => { force!(is_panic_runtime, krate!()); }
1053 DepKind::IsCompilerBuiltins => { force!(is_compiler_builtins, krate!()); }
1054 DepKind::HasGlobalAllocator => { force!(has_global_allocator, krate!()); }
1055 DepKind::ExternCrate => { force!(extern_crate, def_id!()); }
1056 DepKind::LintLevels => { force!(lint_levels, LOCAL_CRATE); }
1057 DepKind::InScopeTraits => { force!(in_scope_traits_map, def_id!().index); }
1058 DepKind::ModuleExports => { force!(module_exports, def_id!()); }
1059 DepKind::IsSanitizerRuntime => { force!(is_sanitizer_runtime, krate!()); }
1060 DepKind::IsProfilerRuntime => { force!(is_profiler_runtime, krate!()); }
1061 DepKind::GetPanicStrategy => { force!(panic_strategy, krate!()); }
1062 DepKind::IsNoBuiltins => { force!(is_no_builtins, krate!()); }
1063 DepKind::ImplDefaultness => { force!(impl_defaultness, def_id!()); }
1064 DepKind::CheckItemWellFormed => { force!(check_item_well_formed, def_id!()); }
1065 DepKind::CheckTraitItemWellFormed => { force!(check_trait_item_well_formed, def_id!()); }
1066 DepKind::CheckImplItemWellFormed => { force!(check_impl_item_well_formed, def_id!()); }
1067 DepKind::ReachableNonGenerics => { force!(reachable_non_generics, krate!()); }
1068 DepKind::NativeLibraries => { force!(native_libraries, krate!()); }
1069 DepKind::PluginRegistrarFn => { force!(plugin_registrar_fn, krate!()); }
1070 DepKind::DeriveRegistrarFn => { force!(derive_registrar_fn, krate!()); }
1071 DepKind::CrateDisambiguator => { force!(crate_disambiguator, krate!()); }
1072 DepKind::CrateHash => { force!(crate_hash, krate!()); }
1073 DepKind::OriginalCrateName => { force!(original_crate_name, krate!()); }
1074 DepKind::ExtraFileName => { force!(extra_filename, krate!()); }
1076 DepKind::AllTraitImplementations => {
1077 force!(all_trait_implementations, krate!());
1080 DepKind::DllimportForeignItems => {
1081 force!(dllimport_foreign_items, krate!());
1083 DepKind::IsDllimportForeignItem => {
1084 force!(is_dllimport_foreign_item, def_id!());
1086 DepKind::IsStaticallyIncludedForeignItem => {
1087 force!(is_statically_included_foreign_item, def_id!());
1089 DepKind::NativeLibraryKind => { force!(native_library_kind, def_id!()); }
1090 DepKind::LinkArgs => { force!(link_args, LOCAL_CRATE); }
1092 DepKind::ResolveLifetimes => { force!(resolve_lifetimes, krate!()); }
1093 DepKind::NamedRegion => { force!(named_region_map, def_id!().index); }
1094 DepKind::IsLateBound => { force!(is_late_bound_map, def_id!().index); }
1095 DepKind::ObjectLifetimeDefaults => {
1096 force!(object_lifetime_defaults_map, def_id!().index);
1099 DepKind::Visibility => { force!(visibility, def_id!()); }
1100 DepKind::DepKind => { force!(dep_kind, krate!()); }
1101 DepKind::CrateName => { force!(crate_name, krate!()); }
1102 DepKind::ItemChildren => { force!(item_children, def_id!()); }
1103 DepKind::ExternModStmtCnum => { force!(extern_mod_stmt_cnum, def_id!()); }
1104 DepKind::GetLangItems => { force!(get_lang_items, LOCAL_CRATE); }
1105 DepKind::DefinedLangItems => { force!(defined_lang_items, krate!()); }
1106 DepKind::MissingLangItems => { force!(missing_lang_items, krate!()); }
1107 DepKind::VisibleParentMap => { force!(visible_parent_map, LOCAL_CRATE); }
1108 DepKind::MissingExternCrateItem => {
1109 force!(missing_extern_crate_item, krate!());
1111 DepKind::UsedCrateSource => { force!(used_crate_source, krate!()); }
1112 DepKind::PostorderCnums => { force!(postorder_cnums, LOCAL_CRATE); }
1114 DepKind::Freevars => { force!(freevars, def_id!()); }
1115 DepKind::MaybeUnusedTraitImport => {
1116 force!(maybe_unused_trait_import, def_id!());
1118 DepKind::MaybeUnusedExternCrates => { force!(maybe_unused_extern_crates, LOCAL_CRATE); }
1119 DepKind::StabilityIndex => { force!(stability_index, LOCAL_CRATE); }
1120 DepKind::AllTraits => { force!(all_traits, LOCAL_CRATE); }
1121 DepKind::AllCrateNums => { force!(all_crate_nums, LOCAL_CRATE); }
1122 DepKind::ExportedSymbols => { force!(exported_symbols, krate!()); }
1123 DepKind::CollectAndPartitionTranslationItems => {
1124 force!(collect_and_partition_translation_items, LOCAL_CRATE);
1126 DepKind::IsTranslatedItem => { force!(is_translated_item, def_id!()); }
1127 DepKind::OutputFilenames => { force!(output_filenames, LOCAL_CRATE); }
1129 DepKind::TargetFeaturesWhitelist => { force!(target_features_whitelist, LOCAL_CRATE); }
1131 DepKind::Features => { force!(features_query, LOCAL_CRATE); }
1133 DepKind::ProgramClausesFor => { force!(program_clauses_for, def_id!()); }
1134 DepKind::WasmCustomSections => { force!(wasm_custom_sections, krate!()); }
1135 DepKind::WasmImportModuleMap => { force!(wasm_import_module_map, krate!()); }
1136 DepKind::ForeignModules => { force!(foreign_modules, krate!()); }
1138 DepKind::UpstreamMonomorphizations => {
1139 force!(upstream_monomorphizations, krate!());
1141 DepKind::UpstreamMonomorphizationsFor => {
1142 force!(upstream_monomorphizations_for, def_id!());
1150 // FIXME(#45015): Another piece of boilerplate code that could be generated in
1151 // a combined define_dep_nodes!()/define_maps!() macro.
1152 macro_rules! impl_load_from_cache {
1153 ($($dep_kind:ident => $query_name:ident,)*) => {
1155 // Check whether the query invocation corresponding to the given
1156 // DepNode is eligible for on-disk-caching.
1157 pub fn cache_on_disk(&self, tcx: TyCtxt) -> bool {
1158 use ty::maps::queries;
1159 use ty::maps::QueryDescription;
1162 $(DepKind::$dep_kind => {
1163 let def_id = self.extract_def_id(tcx).unwrap();
1164 queries::$query_name::cache_on_disk(def_id)
1170 // This is method will execute the query corresponding to the given
1171 // DepNode. It is only expected to work for DepNodes where the
1172 // above `cache_on_disk` methods returns true.
1173 // Also, as a sanity check, it expects that the corresponding query
1174 // invocation has been marked as green already.
1175 pub fn load_from_on_disk_cache(&self, tcx: TyCtxt) {
1177 $(DepKind::$dep_kind => {
1178 debug_assert!(tcx.dep_graph
1180 .map(|c| c.is_green())
1183 let def_id = self.extract_def_id(tcx).unwrap();
1184 let _ = tcx.$query_name(def_id);
1195 impl_load_from_cache!(
1196 TypeckTables => typeck_tables_of,
1197 MirOptimized => optimized_mir,
1198 UnsafetyCheckResult => unsafety_check_result,
1199 BorrowCheck => borrowck,
1200 MirBorrowCheck => mir_borrowck,
1201 MirConstQualif => mir_const_qualif,
1202 SymbolName => def_symbol_name,
1203 ConstIsRvaluePromotableToStatic => const_is_rvalue_promotable_to_static,
1204 CheckMatch => check_match,
1205 TypeOfItem => type_of,
1206 GenericsOfItem => generics_of,
1207 PredicatesOfItem => predicates_of,
1208 UsedTraitImports => used_trait_imports,
1209 TransFnAttrs => trans_fn_attrs,
1210 SpecializationGraph => specialization_graph_of,