Skip to main content

rustc_middle/dep_graph/
graph.rs

1use std::assert_matches;
2use std::fmt::Debug;
3use std::hash::Hash;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU32, Ordering};
6
7use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
8use rustc_data_structures::fx::FxHashSet;
9use rustc_data_structures::profiling::QueryInvocationId;
10use rustc_data_structures::sharded::{self, ShardedHashMap};
11use rustc_data_structures::stable_hash::{StableHash, StableHasher};
12use rustc_data_structures::sync::{AtomicU64, Lock};
13use rustc_data_structures::unord::UnordMap;
14use rustc_errors::DiagInner;
15use rustc_index::IndexVec;
16use rustc_macros::{Decodable, Encodable};
17use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
18use rustc_session::Session;
19use rustc_span::Symbol;
20use tracing::instrument;
21#[cfg(debug_assertions)]
22use {super::debug::EdgeFilter, std::env};
23
24use super::retained::RetainedDepGraph;
25use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex};
26use super::{DepKind, DepNode, WorkProductId, read_deps, with_deps};
27use crate::dep_graph::edges::EdgesVec;
28use crate::ich::StableHashState;
29use crate::ty::TyCtxt;
30use crate::verify_ich::incremental_verify_ich;
31
32/// Tracks 'side effects' for a particular query.
33/// This struct is saved to disk along with the query result,
34/// and loaded from disk if we mark the query as green.
35/// This allows us to 'replay' changes to global state
36/// that would otherwise only occur if we actually
37/// executed the query method.
38///
39/// Each side effect gets an unique dep node index which is added
40/// as a dependency of the query which had the effect.
41#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QuerySideEffect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            QuerySideEffect::Diagnostic(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Diagnostic", &__self_0),
            QuerySideEffect::CheckFeature { symbol: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "CheckFeature", "symbol", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for QuerySideEffect {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        QuerySideEffect::Diagnostic(ref __binding_0) => { 0usize }
                        QuerySideEffect::CheckFeature { symbol: ref __binding_0 } =>
                            {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    QuerySideEffect::Diagnostic(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    QuerySideEffect::CheckFeature { symbol: ref __binding_0 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for QuerySideEffect {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        QuerySideEffect::Diagnostic(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        QuerySideEffect::CheckFeature {
                            symbol: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `QuerySideEffect`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
42pub enum QuerySideEffect {
43    /// Stores a diagnostic emitted during query execution.
44    /// This diagnostic will be re-emitted if we mark
45    /// the query as green, as that query will have the side
46    /// effect dep node as a dependency.
47    Diagnostic(DiagInner),
48    /// Records the feature used during query execution.
49    /// This feature will be inserted into `sess.used_features`
50    /// if we mark the query as green, as that query will have
51    /// the side effect dep node as a dependency.
52    CheckFeature { symbol: Symbol },
53}
54
55#[derive(#[automatically_derived]
impl ::core::clone::Clone for DepGraph {
    #[inline]
    fn clone(&self) -> DepGraph {
        DepGraph {
            data: ::core::clone::Clone::clone(&self.data),
            virtual_dep_node_index: ::core::clone::Clone::clone(&self.virtual_dep_node_index),
        }
    }
}Clone)]
56pub struct DepGraph {
57    data: Option<Arc<DepGraphData>>,
58
59    /// This field is used for assigning DepNodeIndices when running in
60    /// non-incremental mode. Even in non-incremental mode we make sure that
61    /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
62    /// ID is used for self-profiling.
63    virtual_dep_node_index: Arc<AtomicU32>,
64}
65
66impl ::std::fmt::Debug for DepNodeIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
67    pub struct DepNodeIndex {}
68}
69
70// We store a large collection of these in `prev_index_to_index` during
71// non-full incremental builds, and want to ensure that the element size
72// doesn't inadvertently increase.
73const _: [(); 4] = [(); ::std::mem::size_of::<Option<DepNodeIndex>>()];rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
74
75impl DepNodeIndex {
76    const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
77    pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
78}
79
80impl From<DepNodeIndex> for QueryInvocationId {
81    #[inline(always)]
82    fn from(dep_node_index: DepNodeIndex) -> Self {
83        QueryInvocationId(dep_node_index.as_u32())
84    }
85}
86
87pub(crate) struct MarkFrame<'a> {
88    index: SerializedDepNodeIndex,
89    parent: Option<&'a MarkFrame<'a>>,
90}
91
92#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DepNodeColor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DepNodeColor::Green(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Green",
                    &__self_0),
            DepNodeColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
            DepNodeColor::Unknown =>
                ::core::fmt::Formatter::write_str(f, "Unknown"),
        }
    }
}Debug)]
93pub(super) enum DepNodeColor {
94    Green(DepNodeIndex),
95    Red,
96    Unknown,
97}
98
99pub struct DepGraphData {
100    /// The new encoding of the dependency graph, optimized for red/green
101    /// tracking. The `current` field is the dependency graph of only the
102    /// current compilation session: We don't merge the previous dep-graph into
103    /// current one anymore, but we do reference shared data to save space.
104    current: CurrentDepGraph,
105
106    /// The dep-graph from the previous compilation session. It contains all
107    /// nodes and edges as well as all fingerprints of nodes that have them.
108    previous: Arc<SerializedDepGraph>,
109
110    colors: DepNodeColorMap,
111
112    /// When we load, there may be `.o` files, cached MIR, or other such
113    /// things available to us. If we find that they are not dirty, we
114    /// load the path to the file storing those work-products here into
115    /// this map. We can later look for and extract that data.
116    previous_work_products: WorkProductMap,
117
118    /// Used by incremental compilation tests to assert that
119    /// a particular query result was decoded from disk
120    /// (not just marked green)
121    debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
122}
123
124pub fn hash_result<R>(hcx: &mut StableHashState<'_>, result: &R) -> Fingerprint
125where
126    R: StableHash,
127{
128    let mut stable_hasher = StableHasher::new();
129    result.stable_hash(hcx, &mut stable_hasher);
130    stable_hasher.finish()
131}
132
133impl DepGraph {
134    pub fn new(
135        session: &Session,
136        prev_graph: Arc<SerializedDepGraph>,
137        prev_work_products: WorkProductMap,
138        encoder: FileEncoder<'static>,
139    ) -> DepGraph {
140        let prev_graph_node_count = prev_graph.node_count();
141
142        let current =
143            CurrentDepGraph::new(session, prev_graph_node_count, encoder, Arc::clone(&prev_graph));
144
145        let colors = DepNodeColorMap::new(prev_graph_node_count);
146
147        // Instantiate a node with zero dependencies only once for anonymous queries.
148        let _green_node_index = current.alloc_new_node(
149            DepNode { kind: DepKind::AnonZeroDeps, key_fingerprint: current.anon_id_seed.into() },
150            EdgesVec::new(),
151            Fingerprint::ZERO,
152        );
153        match (&_green_node_index, &DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(_green_node_index, DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE);
154
155        // Create a single always-red node, with no dependencies of its own.
156        // Other nodes can use the always-red node as a fake dependency, to
157        // ensure that their dependency list will never be all-green.
158        let red_node_index = current.alloc_new_node(
159            DepNode { kind: DepKind::Red, key_fingerprint: Fingerprint::ZERO.into() },
160            EdgesVec::new(),
161            Fingerprint::ZERO,
162        );
163        match (&red_node_index, &DepNodeIndex::FOREVER_RED_NODE) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(red_node_index, DepNodeIndex::FOREVER_RED_NODE);
164        if prev_graph_node_count > 0 {
165            let prev_index =
166                const { SerializedDepNodeIndex::from_u32(DepNodeIndex::FOREVER_RED_NODE.as_u32()) };
167            let result = colors.try_set_color(prev_index, DesiredColor::Red);
168            {
    match result {
        TrySetColorResult::Success => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TrySetColorResult::Success", ::core::option::Option::None);
        }
    }
};assert_matches!(result, TrySetColorResult::Success);
169        }
170
171        DepGraph {
172            data: Some(Arc::new(DepGraphData {
173                previous_work_products: prev_work_products,
174                current,
175                previous: prev_graph,
176                colors,
177                debug_loaded_from_disk: Default::default(),
178            })),
179            virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
180        }
181    }
182
183    pub fn new_disabled() -> DepGraph {
184        DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
185    }
186
187    #[inline]
188    pub fn data(&self) -> Option<&DepGraphData> {
189        self.data.as_deref()
190    }
191
192    /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
193    #[inline]
194    pub fn is_fully_enabled(&self) -> bool {
195        self.data.is_some()
196    }
197
198    /// Returns a clone of the in-memory retained dep graph, if it is being built
199    /// (i.e. `-Zquery-dep-graph` is set). Cloning rather than exposing the lock keeps
200    /// callers from holding it while forcing queries, which would deadlock against a
201    /// reentrant `record` under the parallel frontend.
202    pub fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
203        self.data.as_ref().and_then(|data| data.current.encoder.retained_dep_graph())
204    }
205
206    pub fn assert_ignored(&self) {
207        if let Some(..) = self.data {
208            read_deps(|task_deps| {
209                {
    match task_deps {
        TaskDepsRef::Ignore => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TaskDepsRef::Ignore",
                ::core::option::Option::Some(format_args!("expected no task dependency tracking")));
        }
    }
};assert_matches!(
210                    task_deps,
211                    TaskDepsRef::Ignore,
212                    "expected no task dependency tracking"
213                );
214            })
215        }
216    }
217
218    pub fn assert_eval_always(&self) {
219        if self.data.is_some() {
220            read_deps(|deps| {
221                {
    match deps {
        TaskDepsRef::EvalAlways => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TaskDepsRef::EvalAlways",
                ::core::option::Option::Some(format_args!("expected eval always context")));
        }
    }
}assert_matches!(deps, TaskDepsRef::EvalAlways, "expected eval always context")
222            });
223        }
224    }
225
226    pub fn with_ignore<OP, R>(&self, op: OP) -> R
227    where
228        OP: FnOnce() -> R,
229    {
230        with_deps(TaskDepsRef::Ignore, op)
231    }
232
233    /// Used to wrap the deserialization of a query result from disk,
234    /// This method enforces that no new `DepNodes` are created during
235    /// query result deserialization.
236    ///
237    /// Enforcing this makes the query dep graph simpler - all nodes
238    /// must be created during the query execution, and should be
239    /// created from inside the 'body' of a query (the implementation
240    /// provided by a particular compiler crate).
241    ///
242    /// Consider the case of three queries `A`, `B`, and `C`, where
243    /// `A` invokes `B` and `B` invokes `C`:
244    ///
245    /// `A -> B -> C`
246    ///
247    /// Suppose that decoding the result of query `B` required re-computing
248    /// the query `C`. If we did not create a fresh `TaskDeps` when
249    /// decoding `B`, we would still be using the `TaskDeps` for query `A`
250    /// (if we needed to re-execute `A`). This would cause us to create
251    /// a new edge `A -> C`. If this edge did not previously
252    /// exist in the `DepGraph`, then we could end up with a different
253    /// `DepGraph` at the end of compilation, even if there were no
254    /// meaningful changes to the overall program (e.g. a newline was added).
255    /// In addition, this edge might cause a subsequent compilation run
256    /// to try to force `C` before marking other necessary nodes green. If
257    /// `C` did not exist in the new compilation session, then we could
258    /// get an ICE. Normally, we would have tried (and failed) to mark
259    /// some other query green (e.g. `item_children`) which was used
260    /// to obtain `C`, which would prevent us from ever trying to force
261    /// a nonexistent `D`.
262    ///
263    /// It might be possible to enforce that all `DepNode`s read during
264    /// deserialization already exist in the previous `DepGraph`. In
265    /// the above example, we would invoke `D` during the deserialization
266    /// of `B`. Since we correctly create a new `TaskDeps` from the decoding
267    /// of `B`, this would result in an edge `B -> D`. If that edge already
268    /// existed (with the same `DepPathHash`es), then it should be correct
269    /// to allow the invocation of the query to proceed during deserialization
270    /// of a query result. We would merely assert that the dep-graph fragment
271    /// that would have been added by invoking `C` while decoding `B`
272    /// is equivalent to the dep-graph fragment that we already instantiated for B
273    /// (at the point where we successfully marked B as green).
274    ///
275    /// However, this would require additional complexity
276    /// in the query infrastructure, and is not currently needed by the
277    /// decoding of any query results. Should the need arise in the future,
278    /// we should consider extending the query system with this functionality.
279    pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
280    where
281        OP: FnOnce() -> R,
282    {
283        with_deps(TaskDepsRef::Forbid, op)
284    }
285
286    #[inline(always)]
287    pub fn with_task<'tcx, OP, R>(
288        &self,
289        dep_node: DepNode,
290        tcx: TyCtxt<'tcx>,
291        op: OP,
292        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
293    ) -> (R, DepNodeIndex)
294    where
295        OP: FnOnce() -> R,
296    {
297        match self.data() {
298            Some(data) => data.with_task(dep_node, tcx, op, hash_result),
299            None => (op(), self.next_virtual_depnode_index()),
300        }
301    }
302
303    pub fn with_anon_task<'tcx, OP, R>(
304        &self,
305        tcx: TyCtxt<'tcx>,
306        dep_kind: DepKind,
307        op: OP,
308    ) -> (R, DepNodeIndex)
309    where
310        OP: FnOnce() -> R,
311    {
312        match self.data() {
313            Some(data) => {
314                let (result, index) = data.with_anon_task_inner(tcx, dep_kind, op);
315                self.read_index(index);
316                (result, index)
317            }
318            None => (op(), self.next_virtual_depnode_index()),
319        }
320    }
321}
322
323impl DepGraphData {
324    #[inline(always)]
325    pub fn with_task<'tcx, OP, R>(
326        &self,
327        dep_node: DepNode,
328        tcx: TyCtxt<'tcx>,
329        op: OP,
330        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
331    ) -> (R, DepNodeIndex)
332    where
333        OP: FnOnce() -> R,
334    {
335        // If the following assertion triggers, it can have two reasons:
336        // 1. Something is wrong with DepNode creation, either here or
337        //    in `DepGraph::try_mark_green()`.
338        // 2. Two distinct query keys get mapped to the same `DepNode`
339        //    (see for example #48923).
340        self.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
341            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("forcing query with already existing `DepNode`: {0:?}",
                dep_node))
    })format!("forcing query with already existing `DepNode`: {dep_node:?}")
342        });
343
344        let (result, edges) = if tcx.is_eval_always(dep_node.kind) {
345            (with_deps(TaskDepsRef::EvalAlways, op), EdgesVec::new())
346        } else {
347            let task_deps = Lock::new(TaskDeps::new(
348                #[cfg(debug_assertions)]
349                Some(dep_node),
350                0,
351            ));
352            (with_deps(TaskDepsRef::Allow(&task_deps), op), task_deps.into_inner().reads)
353        };
354
355        let dep_node_index =
356            self.hash_result_and_alloc_node(tcx, dep_node, edges, &result, hash_result);
357
358        (result, dep_node_index)
359    }
360
361    /// Executes something within an "anonymous" task, that is, a task the
362    /// `DepNode` of which is determined by the list of inputs it read from.
363    ///
364    /// NOTE: this does not actually count as a read of the DepNode here.
365    /// Using the result of this task without reading the DepNode will result
366    /// in untracked dependencies which may lead to ICEs as nodes are
367    /// incorrectly marked green.
368    ///
369    /// FIXME: This could perhaps return a `WithDepNode` to ensure that the
370    /// user of this function actually performs the read.
371    fn with_anon_task_inner<'tcx, OP, R>(
372        &self,
373        tcx: TyCtxt<'tcx>,
374        dep_kind: DepKind,
375        op: OP,
376    ) -> (R, DepNodeIndex)
377    where
378        OP: FnOnce() -> R,
379    {
380        if true {
    if !!tcx.is_eval_always(dep_kind) {
        ::core::panicking::panic("assertion failed: !tcx.is_eval_always(dep_kind)")
    };
};debug_assert!(!tcx.is_eval_always(dep_kind));
381
382        // Large numbers of reads are common enough here that pre-sizing `read_set`
383        // to 128 actually helps perf on some benchmarks.
384        let task_deps = Lock::new(TaskDeps::new(
385            #[cfg(debug_assertions)]
386            None,
387            128,
388        ));
389        let result = with_deps(TaskDepsRef::Allow(&task_deps), op);
390        let task_deps = task_deps.into_inner();
391        let reads = task_deps.reads;
392
393        let dep_node_index = match reads.len() {
394            0 => {
395                // Because the dep-node id of anon nodes is computed from the sets of its
396                // dependencies we already know what the ID of this dependency-less node is
397                // going to be (i.e. equal to the precomputed
398                // `SINGLETON_DEPENDENCYLESS_ANON_NODE`). As a consequence we can skip creating
399                // a `StableHasher` and sending the node through interning.
400                DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE
401            }
402            1 => {
403                // When there is only one dependency, don't bother creating a node.
404                reads[0]
405            }
406            _ => {
407                // The dep node indices are hashed here instead of hashing the dep nodes of the
408                // dependencies. These indices may refer to different nodes per session, but this
409                // isn't a problem here because we that ensure the final dep node hash is per
410                // session only by combining it with the per session `anon_id_seed`. This hash only
411                // need to map the dependencies to a single value on a per session basis.
412                let mut hasher = StableHasher::new();
413                reads.hash(&mut hasher);
414
415                let target_dep_node = DepNode {
416                    kind: dep_kind,
417                    // Fingerprint::combine() is faster than sending Fingerprint
418                    // through the StableHasher (at least as long as StableHasher
419                    // is so slow).
420                    key_fingerprint: self.current.anon_id_seed.combine(hasher.finish()).into(),
421                };
422
423                // The DepNodes generated by the process above are not unique. 2 queries could
424                // have exactly the same dependencies. However, deserialization does not handle
425                // duplicated nodes, so we do the deduplication here directly.
426                //
427                // As anonymous nodes are a small quantity compared to the full dep-graph, the
428                // memory impact of this `anon_node_to_index` map remains tolerable, and helps
429                // us avoid useless growth of the graph with almost-equivalent nodes.
430                self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
431                    self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
432                })
433            }
434        };
435
436        (result, dep_node_index)
437    }
438
439    /// Intern the new `DepNode` with the dependencies up-to-now.
440    fn hash_result_and_alloc_node<'tcx, R>(
441        &self,
442        tcx: TyCtxt<'tcx>,
443        node: DepNode,
444        edges: EdgesVec,
445        result: &R,
446        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
447    ) -> DepNodeIndex {
448        let hashing_timer = tcx.prof.incr_result_hashing();
449        let current_fingerprint = hash_result.map(|hash_result| {
450            tcx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
451        });
452        let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
453        hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
454        dep_node_index
455    }
456}
457
458impl DepGraph {
459    #[inline]
460    pub fn read_index(&self, dep_node_index: DepNodeIndex) {
461        if let Some(ref data) = self.data {
462            read_deps(|task_deps| {
463                let mut task_deps = match task_deps {
464                    TaskDepsRef::Allow(deps) => deps.lock(),
465                    TaskDepsRef::EvalAlways => {
466                        // We don't need to record dependencies of eval_always
467                        // queries. They are re-evaluated unconditionally anyway.
468                        return;
469                    }
470                    TaskDepsRef::Ignore => return,
471                    TaskDepsRef::Forbid => {
472                        // Reading is forbidden in this context. ICE with a useful error message.
473                        panic_on_forbidden_read(data, dep_node_index)
474                    }
475                };
476                let task_deps = &mut *task_deps;
477
478                if truecfg!(debug_assertions) {
479                    data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
480                }
481
482                // Has `dep_node_index` been seen before? Use either a linear scan or a hashset
483                // lookup to determine this. See `TaskDeps::read_set` for details.
484                let new_read = if task_deps.reads.len() <= TaskDeps::LINEAR_SCAN_MAX {
485                    !task_deps.reads.contains(&dep_node_index)
486                } else {
487                    task_deps.read_set.insert(dep_node_index)
488                };
489                if new_read {
490                    task_deps.reads.push(dep_node_index);
491                    if task_deps.reads.len() == TaskDeps::LINEAR_SCAN_MAX + 1 {
492                        // Fill `read_set` with what we have so far. Future lookups will use it.
493                        task_deps.read_set.extend(task_deps.reads.iter().copied());
494                    }
495
496                    #[cfg(debug_assertions)]
497                    {
498                        if let Some(target) = task_deps.node
499                            && let Some(ref forbidden_edge) = data.current.forbidden_edge
500                        {
501                            let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
502                            if forbidden_edge.test(&src, &target) {
503                                {
    ::core::panicking::panic_fmt(format_args!("forbidden edge {0:?} -> {1:?} created",
            src, target));
}panic!("forbidden edge {:?} -> {:?} created", src, target)
504                            }
505                        }
506                    }
507                } else if truecfg!(debug_assertions) {
508                    data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
509                }
510            })
511        }
512    }
513
514    /// This encodes a side effect by creating a node with an unique index and associating
515    /// it with the node, for use in the next session.
516    #[inline]
517    pub fn record_diagnostic<'tcx>(&self, tcx: TyCtxt<'tcx>, diagnostic: &DiagInner) {
518        if let Some(ref data) = self.data {
519            read_deps(|task_deps| match task_deps {
520                TaskDepsRef::EvalAlways | TaskDepsRef::Ignore => return,
521                TaskDepsRef::Forbid | TaskDepsRef::Allow(..) => {
522                    let dep_node_index = data
523                        .encode_side_effect(tcx, QuerySideEffect::Diagnostic(diagnostic.clone()));
524                    self.read_index(dep_node_index);
525                }
526            })
527        }
528    }
529    /// This forces a side effect node green by running its side effect. `prev_index` would
530    /// refer to a node created used `encode_side_effect` in the previous session.
531    #[inline]
532    pub fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
533        if let Some(ref data) = self.data {
534            data.force_side_effect(tcx, prev_index);
535        }
536    }
537
538    #[inline]
539    pub fn encode_side_effect<'tcx>(
540        &self,
541        tcx: TyCtxt<'tcx>,
542        side_effect: QuerySideEffect,
543    ) -> DepNodeIndex {
544        if let Some(ref data) = self.data {
545            data.encode_side_effect(tcx, side_effect)
546        } else {
547            self.next_virtual_depnode_index()
548        }
549    }
550
551    /// Create a node when we force-feed a value into the query cache.
552    /// This is used to remove cycles during type-checking const generic parameters.
553    ///
554    /// As usual in the query system, we consider the current state of the calling query
555    /// only depends on the list of dependencies up to now. As a consequence, the value
556    /// that this query gives us can only depend on those dependencies too. Therefore,
557    /// it is sound to use the current dependency set for the created node.
558    ///
559    /// During replay, the order of the nodes is relevant in the dependency graph.
560    /// So the unchanged replay will mark the caller query before trying to mark this one.
561    /// If there is a change to report, the caller query will be re-executed before this one.
562    ///
563    /// FIXME: If the code is changed enough for this node to be marked before requiring the
564    /// caller's node, we suppose that those changes will be enough to mark this node red and
565    /// force a recomputation using the "normal" way.
566    pub fn with_feed_task<'tcx, R>(
567        &self,
568        node: DepNode,
569        tcx: TyCtxt<'tcx>,
570        result: &R,
571        hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
572        format_value_fn: fn(&R) -> String,
573    ) -> DepNodeIndex {
574        if let Some(data) = self.data.as_ref() {
575            // The caller query has more dependencies than the node we are creating. We may
576            // encounter a case where this created node is marked as green, but the caller query is
577            // subsequently marked as red or recomputed. In this case, we will end up feeding a
578            // value to an existing node.
579            //
580            // For sanity, we still check that the loaded stable hash and the new one match.
581            if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
582                let dep_node_index = data.colors.current(prev_index);
583                if let Some(dep_node_index) = dep_node_index {
584                    incremental_verify_ich(
585                        tcx,
586                        data,
587                        result,
588                        prev_index,
589                        hash_result,
590                        format_value_fn,
591                    );
592
593                    #[cfg(debug_assertions)]
594                    if hash_result.is_some() {
595                        data.current.record_edge(
596                            dep_node_index,
597                            node,
598                            data.prev_value_fingerprint_of(prev_index),
599                        );
600                    }
601
602                    return dep_node_index;
603                }
604            }
605
606            let mut edges = EdgesVec::new();
607            read_deps(|task_deps| match task_deps {
608                TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()),
609                TaskDepsRef::EvalAlways => {
610                    edges.push(DepNodeIndex::FOREVER_RED_NODE);
611                }
612                TaskDepsRef::Ignore => {}
613                TaskDepsRef::Forbid => {
614                    {
    ::core::panicking::panic_fmt(format_args!("Cannot summarize when dependencies are not recorded."));
}panic!("Cannot summarize when dependencies are not recorded.")
615                }
616            });
617
618            data.hash_result_and_alloc_node(tcx, node, edges, result, hash_result)
619        } else {
620            // Incremental compilation is turned off. We just execute the task
621            // without tracking. We still provide a dep-node index that uniquely
622            // identifies the task so that we have a cheap way of referring to
623            // the query for self-profiling.
624            self.next_virtual_depnode_index()
625        }
626    }
627}
628
629impl DepGraphData {
630    fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
631        &self,
632        sess: &Session,
633        dep_node: &DepNode,
634        msg: impl FnOnce() -> S,
635    ) {
636        if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
637            let color = self.colors.get(prev_index);
638            let ok = match color {
639                DepNodeColor::Unknown => true,
640                DepNodeColor::Red => false,
641                DepNodeColor::Green(..) => sess.threads().is_some(), // Other threads may mark this green
642            };
643            if !ok {
644                { ::core::panicking::panic_display(&msg()); }panic!("{}", msg())
645            }
646        }
647    }
648
649    fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
650        if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
651            self.colors.get(prev_index)
652        } else {
653            // This is a node that did not exist in the previous compilation session.
654            DepNodeColor::Unknown
655        }
656    }
657
658    /// Returns true if the given node has been marked as green during the
659    /// current compilation session. Used in various assertions
660    #[inline]
661    pub fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
662        #[allow(non_exhaustive_omitted_patterns)] match self.colors.get(prev_index) {
    DepNodeColor::Green(_) => true,
    _ => false,
}matches!(self.colors.get(prev_index), DepNodeColor::Green(_))
663    }
664
665    #[inline]
666    pub fn prev_value_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
667        self.previous.value_fingerprint_for_index(prev_index)
668    }
669
670    #[inline]
671    pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> &DepNode {
672        self.previous.index_to_node(prev_index)
673    }
674
675    pub fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
676        self.debug_loaded_from_disk.lock().insert(dep_node);
677    }
678
679    /// This encodes a side effect by creating a node with an unique index and associating
680    /// it with the node, for use in the next session.
681    #[inline]
682    fn encode_side_effect<'tcx>(
683        &self,
684        tcx: TyCtxt<'tcx>,
685        side_effect: QuerySideEffect,
686    ) -> DepNodeIndex {
687        // Use `send_new` so we get an unique index, even though the dep node is not.
688        let dep_node_index = self.current.encoder.send_new(
689            DepNode {
690                kind: DepKind::SideEffect,
691                key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
692            },
693            Fingerprint::ZERO,
694            // We want the side effect node to always be red so it will be forced and run the
695            // side effect.
696            std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
697        );
698        tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
699        dep_node_index
700    }
701
702    /// This forces a side effect node green by running its side effect. `prev_index` would
703    /// refer to a node created used `encode_side_effect` in the previous session.
704    #[inline]
705    fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
706        with_deps(TaskDepsRef::Ignore, || {
707            let side_effect = tcx
708                .query_system
709                .on_disk_cache
710                .as_ref()
711                .unwrap()
712                .load_side_effect(tcx, prev_index)
713                .unwrap();
714
715            // Use `send_and_color` as `promote_node_and_deps_to_current` expects all
716            // green dependencies. `send_and_color` will also prevent multiple nodes
717            // being encoded for concurrent calls.
718            let dep_node_index = self.current.encoder.send_and_color(
719                prev_index,
720                &self.colors,
721                DepNode {
722                    kind: DepKind::SideEffect,
723                    key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
724                },
725                Fingerprint::ZERO,
726                std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
727                true,
728            );
729
730            match &side_effect {
731                QuerySideEffect::Diagnostic(diagnostic) => {
732                    tcx.dcx().emit_diagnostic(diagnostic.clone());
733                }
734                QuerySideEffect::CheckFeature { symbol } => {
735                    tcx.sess.used_features.lock().insert(*symbol, dep_node_index.as_u32());
736                }
737            }
738
739            // This will just overwrite the same value for concurrent calls.
740            tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
741        })
742    }
743
744    fn alloc_and_color_node(
745        &self,
746        key: DepNode,
747        edges: EdgesVec,
748        value_fingerprint: Option<Fingerprint>,
749    ) -> DepNodeIndex {
750        if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
751            // Determine the color and index of the new `DepNode`.
752            let is_green = if let Some(value_fingerprint) = value_fingerprint {
753                if value_fingerprint == self.previous.value_fingerprint_for_index(prev_index) {
754                    // This is a green node: it existed in the previous compilation,
755                    // its query was re-executed, and it has the same result as before.
756                    true
757                } else {
758                    // This is a red node: it existed in the previous compilation, its query
759                    // was re-executed, but it has a different result from before.
760                    false
761                }
762            } else {
763                // This is a red node, effectively: it existed in the previous compilation
764                // session, its query was re-executed, but it doesn't compute a result hash
765                // (i.e. it represents a `no_hash` query), so we have no way of determining
766                // whether or not the result was the same as before.
767                false
768            };
769
770            let value_fingerprint = value_fingerprint.unwrap_or(Fingerprint::ZERO);
771
772            let dep_node_index = self.current.encoder.send_and_color(
773                prev_index,
774                &self.colors,
775                key,
776                value_fingerprint,
777                edges,
778                is_green,
779            );
780
781            #[cfg(debug_assertions)]
782            self.current.record_edge(dep_node_index, key, value_fingerprint);
783
784            dep_node_index
785        } else {
786            self.current.alloc_new_node(key, edges, value_fingerprint.unwrap_or(Fingerprint::ZERO))
787        }
788    }
789
790    fn promote_node_and_deps_to_current(
791        &self,
792        prev_index: SerializedDepNodeIndex,
793    ) -> Option<DepNodeIndex> {
794        let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors);
795
796        #[cfg(debug_assertions)]
797        if let Some(dep_node_index) = dep_node_index {
798            self.current.record_edge(
799                dep_node_index,
800                *self.previous.index_to_node(prev_index),
801                self.previous.value_fingerprint_for_index(prev_index),
802            );
803        }
804
805        dep_node_index
806    }
807}
808
809impl DepGraph {
810    /// Checks whether a previous work product exists for `v` and, if
811    /// so, return the path that leads to it. Used to skip doing work.
812    pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
813        self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
814    }
815
816    /// Access the map of work-products created during the cached run. Only
817    /// used during saving of the dep-graph.
818    pub fn previous_work_products(&self) -> &WorkProductMap {
819        &self.data.as_ref().unwrap().previous_work_products
820    }
821
822    pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
823        self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
824    }
825
826    pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool {
827        // We only check if we have a dep node corresponding to the given dep kind.
828        #[allow(rustc::potential_query_instability)]
829        self.data
830            .as_ref()
831            .unwrap()
832            .debug_loaded_from_disk
833            .lock()
834            .iter()
835            .any(|node| node.kind == dep_kind)
836    }
837
838    fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
839        if let Some(ref data) = self.data {
840            return data.node_color(dep_node);
841        }
842
843        DepNodeColor::Unknown
844    }
845
846    pub fn try_mark_green<'tcx>(
847        &self,
848        tcx: TyCtxt<'tcx>,
849        dep_node: &DepNode,
850    ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
851        self.data()?.try_mark_green(tcx, dep_node)
852    }
853}
854
855impl DepGraphData {
856    /// Try to mark a node index for the node dep_node.
857    ///
858    /// A node will have an index, when it's already been marked green, or when we can mark it
859    /// green. This function will mark the current task as a reader of the specified node, when
860    /// a node index can be found for that node.
861    pub fn try_mark_green<'tcx>(
862        &self,
863        tcx: TyCtxt<'tcx>,
864        dep_node: &DepNode,
865    ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
866        if true {
    if !!tcx.is_eval_always(dep_node.kind) {
        ::core::panicking::panic("assertion failed: !tcx.is_eval_always(dep_node.kind)")
    };
};debug_assert!(!tcx.is_eval_always(dep_node.kind));
867
868        // Return None if the dep node didn't exist in the previous session
869        let prev_index = self.previous.node_to_index_opt(dep_node)?;
870
871        if true {
    match (&self.previous.index_to_node(prev_index), &dep_node) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(self.previous.index_to_node(prev_index), dep_node);
872
873        match self.colors.get(prev_index) {
874            DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
875            DepNodeColor::Red => None,
876            DepNodeColor::Unknown => {
877                // This DepNode and the corresponding query invocation existed
878                // in the previous compilation session too, so we can try to
879                // mark it as green by recursively marking all of its
880                // dependencies green.
881                self.try_mark_previous_green(tcx, prev_index, None)
882                    .map(|dep_node_index| (prev_index, dep_node_index))
883            }
884        }
885    }
886
887    /// Try to mark a dep-node which existed in the previous compilation session as green.
888    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("try_mark_previous_green",
                                    "rustc_middle::dep_graph::graph", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/graph.rs"),
                                    ::tracing_core::__macro_support::Option::Some(888u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<DepNodeIndex> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let frame =
                MarkFrame { index: prev_dep_node_index, parent: frame };
            if true {
                if !!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)
                    {
                    ::core::panicking::panic("assertion failed: !tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)")
                };
            };
            for parent_dep_node_index in
                self.previous.edge_targets_from(prev_dep_node_index) {
                match self.colors.get(parent_dep_node_index) {
                    DepNodeColor::Green(_) => continue,
                    DepNodeColor::Red => return None,
                    DepNodeColor::Unknown => {}
                }
                let parent_dep_node =
                    self.previous.index_to_node(parent_dep_node_index);
                if !tcx.is_eval_always(parent_dep_node.kind) &&
                        self.try_mark_previous_green(tcx, parent_dep_node_index,
                                Some(&frame)).is_some() {
                    continue;
                }
                if !tcx.try_force_from_dep_node(*parent_dep_node,
                            parent_dep_node_index, &frame) {
                    return None;
                }
                match self.colors.get(parent_dep_node_index) {
                    DepNodeColor::Green(_) => continue,
                    DepNodeColor::Red => return None,
                    DepNodeColor::Unknown => {}
                }
                if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
                    {
                        ::core::panicking::panic_fmt(format_args!("try_mark_previous_green() - forcing failed to set a color"));
                    };
                }
                return None;
            }
            let dep_node_index =
                self.promote_node_and_deps_to_current(prev_dep_node_index)?;
            Some(dep_node_index)
        }
    }
}#[instrument(skip(self, tcx, prev_dep_node_index, frame), level = "debug")]
889    fn try_mark_previous_green<'tcx>(
890        &self,
891        tcx: TyCtxt<'tcx>,
892        prev_dep_node_index: SerializedDepNodeIndex,
893        frame: Option<&MarkFrame<'_>>,
894    ) -> Option<DepNodeIndex> {
895        let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
896
897        // We never try to mark eval_always nodes as green
898        debug_assert!(!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind));
899
900        for parent_dep_node_index in self.previous.edge_targets_from(prev_dep_node_index) {
901            match self.colors.get(parent_dep_node_index) {
902                // This dependency has been marked as green before, we are still ok and can
903                // continue checking the remaining dependencies.
904                DepNodeColor::Green(_) => continue,
905
906                // This dependency's result is different to the previous compilation session. We
907                // cannot mark this dep_node as green, so stop checking.
908                DepNodeColor::Red => return None,
909
910                // We still need to determine this dependency's colour.
911                DepNodeColor::Unknown => {}
912            }
913
914            let parent_dep_node = self.previous.index_to_node(parent_dep_node_index);
915
916            // If this dependency isn't eval_always, try to mark it green recursively.
917            if !tcx.is_eval_always(parent_dep_node.kind)
918                && self.try_mark_previous_green(tcx, parent_dep_node_index, Some(&frame)).is_some()
919            {
920                continue;
921            }
922
923            // We failed to mark it green, so we try to force the query.
924            if !tcx.try_force_from_dep_node(*parent_dep_node, parent_dep_node_index, &frame) {
925                return None;
926            }
927
928            match self.colors.get(parent_dep_node_index) {
929                DepNodeColor::Green(_) => continue,
930                DepNodeColor::Red => return None,
931                DepNodeColor::Unknown => {}
932            }
933
934            if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
935                panic!("try_mark_previous_green() - forcing failed to set a color");
936            }
937
938            // If the query we just forced has resulted in some kind of compilation error, we
939            // cannot rely on the dep-node color having been properly updated. This means that the
940            // query system has reached an invalid state. We let the compiler continue (by
941            // returning `None`) so it can emit error messages and wind down, but rely on the fact
942            // that this invalid state will not be persisted to the incremental compilation cache
943            // because of compilation errors being present.
944            return None;
945        }
946
947        // If we got here without hitting a `return` that means that all
948        // dependencies of this DepNode could be marked as green. Therefore we
949        // can also mark this DepNode as green.
950
951        // There may be multiple threads trying to mark the same dep node green concurrently.
952
953        // We allocating an entry for the node in the current dependency graph and
954        // adding all the appropriate edges imported from the previous graph.
955        //
956        // `no_hash` nodes may fail this promotion due to already being conservatively colored red.
957        let dep_node_index = self.promote_node_and_deps_to_current(prev_dep_node_index)?;
958
959        // ... and finally storing a "Green" entry in the color map.
960        // Multiple threads can all write the same color here.
961
962        Some(dep_node_index)
963    }
964}
965
966impl DepGraph {
967    /// Returns true if the given node has been marked as red during the
968    /// current compilation session. Used in various assertions
969    pub fn is_red(&self, dep_node: &DepNode) -> bool {
970        #[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
    DepNodeColor::Red => true,
    _ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Red)
971    }
972
973    /// Returns true if the given node has been marked as green during the
974    /// current compilation session. Used in various assertions
975    pub fn is_green(&self, dep_node: &DepNode) -> bool {
976        #[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
    DepNodeColor::Green(_) => true,
    _ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Green(_))
977    }
978
979    pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
980        &self,
981        sess: &Session,
982        dep_node: &DepNode,
983        msg: impl FnOnce() -> S,
984    ) {
985        if let Some(data) = &self.data {
986            data.assert_dep_node_not_yet_allocated_in_current_session(sess, dep_node, msg)
987        }
988    }
989
990    /// This method loads all on-disk cacheable query results into memory, so
991    /// they can be written out to the new cache file again. Most query results
992    /// will already be in memory but in the case where we marked something as
993    /// green but then did not need the value, that value will never have been
994    /// loaded from disk.
995    ///
996    /// This method will only load queries that will end up in the disk cache.
997    /// Other queries will not be executed.
998    pub fn exec_cache_promotions<'tcx>(&self, tcx: TyCtxt<'tcx>) {
999        let _prof_timer = tcx.prof.generic_activity("incr_comp_query_cache_promotion");
1000
1001        let data = self.data.as_ref().unwrap();
1002        for prev_index in data.colors.values.indices() {
1003            match data.colors.get(prev_index) {
1004                DepNodeColor::Green(_) => {
1005                    let dep_node = data.previous.index_to_node(prev_index);
1006                    if let Some(promote_fn) =
1007                        tcx.dep_kind_vtable(dep_node.kind).promote_from_disk_fn
1008                    {
1009                        promote_fn(tcx, *dep_node)
1010                    };
1011                }
1012                DepNodeColor::Unknown | DepNodeColor::Red => {
1013                    // We can skip red nodes because a node can only be marked
1014                    // as red if the query result was recomputed and thus is
1015                    // already in memory.
1016                }
1017            }
1018        }
1019    }
1020
1021    pub(crate) fn finish_encoding(&self) -> FileEncodeResult {
1022        if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1023    }
1024
1025    pub fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1026        if true {
    if !self.data.is_none() {
        ::core::panicking::panic("assertion failed: self.data.is_none()")
    };
};debug_assert!(self.data.is_none());
1027        let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1028        DepNodeIndex::from_u32(index)
1029    }
1030}
1031
1032/// A "work product" is an intermediate result that we save into the
1033/// incremental directory for later re-use. The primary example are
1034/// the object files that we save for each partition at code
1035/// generation time.
1036///
1037/// Each work product is associated with a dep-node, representing the
1038/// process that produced the work-product. If that dep-node is found
1039/// to be dirty when we load up, then we will delete the work-product
1040/// at load time. If the work-product is found to be clean, then we
1041/// will keep a record in the `previous_work_products` list.
1042///
1043/// In addition, work products have an associated hash. This hash is
1044/// an extra hash that can be used to decide if the work-product from
1045/// a previous compilation can be re-used (in addition to the dirty
1046/// edges check).
1047///
1048/// As the primary example, consider the object files we generate for
1049/// each partition. In the first run, we create partitions based on
1050/// the symbols that need to be compiled. For each partition P, we
1051/// hash the symbols in P and create a `WorkProduct` record associated
1052/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1053/// in P.
1054///
1055/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1056/// judged to be clean (which means none of the things we read to
1057/// generate the partition were found to be dirty), it will be loaded
1058/// into previous work products. We will then regenerate the set of
1059/// symbols in the partition P and hash them (note that new symbols
1060/// may be added -- for example, new monomorphizations -- even if
1061/// nothing in P changed!). We will compare that hash against the
1062/// previous hash. If it matches up, we can reuse the object file.
1063#[derive(#[automatically_derived]
impl ::core::clone::Clone for WorkProduct {
    #[inline]
    fn clone(&self) -> WorkProduct {
        WorkProduct {
            cgu_name: ::core::clone::Clone::clone(&self.cgu_name),
            saved_files: ::core::clone::Clone::clone(&self.saved_files),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WorkProduct {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "WorkProduct",
            "cgu_name", &self.cgu_name, "saved_files", &&self.saved_files)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for WorkProduct {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    WorkProduct {
                        cgu_name: ref __binding_0, saved_files: ref __binding_1 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for WorkProduct {
            fn decode(__decoder: &mut __D) -> Self {
                WorkProduct {
                    cgu_name: ::rustc_serialize::Decodable::decode(__decoder),
                    saved_files: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
1064pub struct WorkProduct {
1065    pub cgu_name: String,
1066    /// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1067    /// saved file and the key is some identifier for the type of file being saved.
1068    ///
1069    /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1070    /// the object file's path, and "dwo" to the dwarf object file's path.
1071    pub saved_files: UnordMap<String, String>,
1072}
1073
1074pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
1075
1076// Index type for `DepNodeData`'s edges.
1077impl ::std::fmt::Debug for EdgeIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
1078    struct EdgeIndex {}
1079}
1080
1081/// `CurrentDepGraph` stores the dependency graph for the current session. It
1082/// will be populated as we run queries or tasks. We never remove nodes from the
1083/// graph: they are only added.
1084///
1085/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1086/// in memory. This is important, because these graph structures are some of the
1087/// largest in the compiler.
1088///
1089/// For this reason, we avoid storing `DepNode`s more than once as map
1090/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1091/// graph, and we map nodes in the previous graph to indices via a two-step
1092/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1093/// and the `prev_index_to_index` vector (which is more compact and faster than
1094/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1095///
1096/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1097/// and `prev_index_to_index` fields are locked separately. Operations that take
1098/// a `DepNodeIndex` typically just access the `data` field.
1099///
1100/// We only need to manipulate at most two locks simultaneously:
1101/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1102/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1103/// first, and `data` second.
1104pub(super) struct CurrentDepGraph {
1105    encoder: GraphEncoder,
1106    anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
1107
1108    /// This is used to verify that value fingerprints do not change between the
1109    /// creation of a node and its recomputation.
1110    #[cfg(debug_assertions)]
1111    value_fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
1112
1113    /// Used to trap when a specific edge is added to the graph.
1114    /// This is used for debug purposes and is only active with `debug_assertions`.
1115    #[cfg(debug_assertions)]
1116    forbidden_edge: Option<EdgeFilter>,
1117
1118    /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1119    /// their edges. This has the beneficial side-effect that multiple anonymous
1120    /// nodes can be coalesced into one without changing the semantics of the
1121    /// dependency graph. However, the merging of nodes can lead to a subtle
1122    /// problem during red-green marking: The color of an anonymous node from
1123    /// the current session might "shadow" the color of the node with the same
1124    /// ID from the previous session. In order to side-step this problem, we make
1125    /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1126    /// This is implemented by mixing a session-key into the ID fingerprint of
1127    /// each anon node. The session-key is a hash of the number of previous sessions.
1128    anon_id_seed: Fingerprint,
1129
1130    /// These are simple counters that are for profiling and
1131    /// debugging and only active with `debug_assertions`.
1132    pub(super) total_read_count: AtomicU64,
1133    pub(super) total_duplicate_read_count: AtomicU64,
1134}
1135
1136impl CurrentDepGraph {
1137    fn new(
1138        session: &Session,
1139        prev_graph_node_count: usize,
1140        encoder: FileEncoder<'static>,
1141        previous: Arc<SerializedDepGraph>,
1142    ) -> Self {
1143        let mut stable_hasher = StableHasher::new();
1144        previous.session_count().hash(&mut stable_hasher);
1145        let anon_id_seed = stable_hasher.finish();
1146
1147        #[cfg(debug_assertions)]
1148        let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1149            Ok(s) => match EdgeFilter::new(&s) {
1150                Ok(f) => Some(f),
1151                Err(err) => {
    ::core::panicking::panic_fmt(format_args!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {0}",
            err));
}panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1152            },
1153            Err(_) => None,
1154        };
1155
1156        let new_node_count_estimate = 102 * prev_graph_node_count / 100 + 200;
1157
1158        CurrentDepGraph {
1159            encoder: GraphEncoder::new(session, encoder, prev_graph_node_count, previous),
1160            anon_node_to_index: ShardedHashMap::with_capacity(
1161                // FIXME: The count estimate is off as anon nodes are only a portion of the nodes.
1162                new_node_count_estimate / sharded::shards(),
1163            ),
1164            anon_id_seed,
1165            #[cfg(debug_assertions)]
1166            forbidden_edge,
1167            #[cfg(debug_assertions)]
1168            value_fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1169            total_read_count: AtomicU64::new(0),
1170            total_duplicate_read_count: AtomicU64::new(0),
1171        }
1172    }
1173
1174    #[cfg(debug_assertions)]
1175    fn record_edge(
1176        &self,
1177        dep_node_index: DepNodeIndex,
1178        key: DepNode,
1179        value_fingerprint: Fingerprint,
1180    ) {
1181        if let Some(forbidden_edge) = &self.forbidden_edge {
1182            forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1183        }
1184        let prior_value_fingerprint = *self
1185            .value_fingerprints
1186            .lock()
1187            .get_or_insert_with(dep_node_index, || value_fingerprint);
1188        match (&prior_value_fingerprint, &value_fingerprint) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::Some(format_args!("Unstable fingerprints for {0:?}",
                        key)));
        }
    }
};assert_eq!(prior_value_fingerprint, value_fingerprint, "Unstable fingerprints for {key:?}");
1189    }
1190
1191    /// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1192    /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1193    #[inline(always)]
1194    fn alloc_new_node(
1195        &self,
1196        key: DepNode,
1197        edges: EdgesVec,
1198        value_fingerprint: Fingerprint,
1199    ) -> DepNodeIndex {
1200        let dep_node_index = self.encoder.send_new(key, value_fingerprint, edges);
1201
1202        #[cfg(debug_assertions)]
1203        self.record_edge(dep_node_index, key, value_fingerprint);
1204
1205        dep_node_index
1206    }
1207}
1208
1209#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for TaskDepsRef<'a> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TaskDepsRef::Allow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
                    &__self_0),
            TaskDepsRef::EvalAlways =>
                ::core::fmt::Formatter::write_str(f, "EvalAlways"),
            TaskDepsRef::Ignore =>
                ::core::fmt::Formatter::write_str(f, "Ignore"),
            TaskDepsRef::Forbid =>
                ::core::fmt::Formatter::write_str(f, "Forbid"),
        }
    }
}Debug, #[automatically_derived]
impl<'a> ::core::clone::Clone for TaskDepsRef<'a> {
    #[inline]
    fn clone(&self) -> TaskDepsRef<'a> {
        let _: ::core::clone::AssertParamIsClone<&'a Lock<TaskDeps>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for TaskDepsRef<'a> { }Copy)]
1210pub enum TaskDepsRef<'a> {
1211    /// New dependencies can be added to the
1212    /// `TaskDeps`. This is used when executing a 'normal' query
1213    /// (no `eval_always` modifier)
1214    Allow(&'a Lock<TaskDeps>),
1215    /// This is used when executing an `eval_always` query. We don't
1216    /// need to track dependencies for a query that's always
1217    /// re-executed -- but we need to know that this is an `eval_always`
1218    /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1219    /// when directly feeding other queries.
1220    EvalAlways,
1221    /// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1222    Ignore,
1223    /// Any attempt to add new dependencies will cause a panic.
1224    /// This is used when decoding a query result from disk,
1225    /// to ensure that the decoding process doesn't itself
1226    /// require the execution of any queries.
1227    Forbid,
1228}
1229
1230#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TaskDeps {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "TaskDeps",
            "node", &self.node, "reads", &self.reads, "read_set",
            &&self.read_set)
    }
}Debug)]
1231pub struct TaskDeps {
1232    #[cfg(debug_assertions)]
1233    node: Option<DepNode>,
1234
1235    /// A vector of `DepNodeIndex`, basically. Contains no duplicates.
1236    reads: EdgesVec,
1237
1238    /// When adding a new edge to `reads` in `DepGraph::read_index` we must determine if the edge
1239    /// has been seen before. We just do a linear scan of `reads` if its length is less than or
1240    /// equal to `LINEAR_SCAN_MAX`. Otherwise, we use this hashset for better performance. Note:
1241    /// `reads` is always the canonical edges representation; this field is just to speed up the
1242    /// seen-before test.
1243    read_set: FxHashSet<DepNodeIndex>,
1244}
1245
1246impl TaskDeps {
1247    /// See `TaskDeps::read_set` above.
1248    const LINEAR_SCAN_MAX: usize = 16;
1249
1250    #[inline]
1251    fn new(#[cfg(debug_assertions)] node: Option<DepNode>, read_set_capacity: usize) -> Self {
1252        TaskDeps {
1253            #[cfg(debug_assertions)]
1254            node,
1255            reads: EdgesVec::new(),
1256            read_set: FxHashSet::with_capacity_and_hasher(read_set_capacity, Default::default()),
1257        }
1258    }
1259}
1260
1261// A data structure that stores Option<DepNodeColor> values as a contiguous
1262// array, using one u32 per entry.
1263pub(super) struct DepNodeColorMap {
1264    values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1265}
1266
1267// All values below `COMPRESSED_RED` are green.
1268const COMPRESSED_RED: u32 = u32::MAX - 1;
1269const COMPRESSED_UNKNOWN: u32 = u32::MAX;
1270
1271impl DepNodeColorMap {
1272    fn new(size: usize) -> DepNodeColorMap {
1273        if true {
    if !(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32) {
        ::core::panicking::panic("assertion failed: COMPRESSED_RED > DepNodeIndex::MAX_AS_U32")
    };
};debug_assert!(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32);
1274        DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1275    }
1276
1277    #[inline]
1278    pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1279        let value = self.values[index].load(Ordering::Relaxed);
1280        if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1281    }
1282
1283    /// Atomically sets the color of a previous-session dep node to either green
1284    /// or red, if it has not already been colored.
1285    ///
1286    /// If the node already has a color, the new color is ignored, and the
1287    /// return value indicates the existing color.
1288    #[inline(always)]
1289    pub(super) fn try_set_color(
1290        &self,
1291        prev_index: SerializedDepNodeIndex,
1292        color: DesiredColor,
1293    ) -> TrySetColorResult {
1294        match self.values[prev_index].compare_exchange(
1295            COMPRESSED_UNKNOWN,
1296            match color {
1297                DesiredColor::Red => COMPRESSED_RED,
1298                DesiredColor::Green { index } => index.as_u32(),
1299            },
1300            Ordering::Relaxed,
1301            Ordering::Relaxed,
1302        ) {
1303            Ok(_) => TrySetColorResult::Success,
1304            Err(COMPRESSED_RED) => TrySetColorResult::AlreadyRed,
1305            Err(index) => TrySetColorResult::AlreadyGreen { index: DepNodeIndex::from_u32(index) },
1306        }
1307    }
1308
1309    #[inline]
1310    pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1311        let value = self.values[index].load(Ordering::Acquire);
1312        // Green is by far the most common case. Check for that first so we can succeed with a
1313        // single comparison.
1314        if value < COMPRESSED_RED {
1315            DepNodeColor::Green(DepNodeIndex::from_u32(value))
1316        } else if value == COMPRESSED_RED {
1317            DepNodeColor::Red
1318        } else {
1319            if true {
    match (&value, &COMPRESSED_UNKNOWN) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(value, COMPRESSED_UNKNOWN);
1320            DepNodeColor::Unknown
1321        }
1322    }
1323}
1324
1325/// The color that [`DepNodeColorMap::try_set_color`] should try to apply to a node.
1326#[derive(#[automatically_derived]
impl ::core::clone::Clone for DesiredColor {
    #[inline]
    fn clone(&self) -> DesiredColor {
        let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DesiredColor { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for DesiredColor {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DesiredColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
            DesiredColor::Green { index: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Green",
                    "index", &__self_0),
        }
    }
}Debug)]
1327pub(super) enum DesiredColor {
1328    /// Try to mark the node red.
1329    Red,
1330    /// Try to mark the node green, associating it with a current-session node index.
1331    Green { index: DepNodeIndex },
1332}
1333
1334/// Return value of [`DepNodeColorMap::try_set_color`], indicating success or failure,
1335/// and (on failure) what the existing color is.
1336#[derive(#[automatically_derived]
impl ::core::clone::Clone for TrySetColorResult {
    #[inline]
    fn clone(&self) -> TrySetColorResult {
        let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrySetColorResult { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for TrySetColorResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            TrySetColorResult::Success =>
                ::core::fmt::Formatter::write_str(f, "Success"),
            TrySetColorResult::AlreadyRed =>
                ::core::fmt::Formatter::write_str(f, "AlreadyRed"),
            TrySetColorResult::AlreadyGreen { index: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AlreadyGreen", "index", &__self_0),
        }
    }
}Debug)]
1337pub(super) enum TrySetColorResult {
1338    /// The [`DesiredColor`] was freshly applied to the node.
1339    Success,
1340    /// Coloring failed because the node was already marked red.
1341    AlreadyRed,
1342    /// Coloring failed because the node was already marked green,
1343    /// and corresponds to node `index` in the current-session dep graph.
1344    AlreadyGreen { index: DepNodeIndex },
1345}
1346
1347#[inline(never)]
1348#[cold]
1349pub(crate) fn print_markframe_trace(graph: &DepGraph, frame: &MarkFrame<'_>) {
1350    let data = graph.data.as_ref().unwrap();
1351
1352    {
    ::std::io::_eprint(format_args!("there was a panic while trying to force a dep node\n"));
};eprintln!("there was a panic while trying to force a dep node");
1353    { ::std::io::_eprint(format_args!("try_mark_green dep node stack:\n")); };eprintln!("try_mark_green dep node stack:");
1354
1355    let mut i = 0;
1356    let mut current = Some(frame);
1357    while let Some(frame) = current {
1358        let node = data.previous.index_to_node(frame.index);
1359        { ::std::io::_eprint(format_args!("#{0} {1:?}\n", i, node)); };eprintln!("#{i} {node:?}");
1360        current = frame.parent;
1361        i += 1;
1362    }
1363
1364    {
    ::std::io::_eprint(format_args!("end of try_mark_green dep node stack\n"));
};eprintln!("end of try_mark_green dep node stack");
1365}
1366
1367#[cold]
1368#[inline(never)]
1369fn panic_on_forbidden_read(data: &DepGraphData, dep_node_index: DepNodeIndex) -> ! {
1370    // We have to do an expensive reverse-lookup of the DepNode that
1371    // corresponds to `dep_node_index`, but that's OK since we are about
1372    // to ICE anyway.
1373    let mut dep_node = None;
1374
1375    // First try to find the dep node among those that already existed in the
1376    // previous session and has been marked green
1377    for prev_index in data.colors.values.indices() {
1378        if data.colors.current(prev_index) == Some(dep_node_index) {
1379            dep_node = Some(*data.previous.index_to_node(prev_index));
1380            break;
1381        }
1382    }
1383
1384    let dep_node = dep_node.map_or_else(
1385        || ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("with index {0:?}", dep_node_index))
    })format!("with index {:?}", dep_node_index),
1386        |dep_node| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0:?}`", dep_node))
    })format!("`{:?}`", dep_node),
1387    );
1388
1389    {
    ::core::panicking::panic_fmt(format_args!("Error: trying to record dependency on DepNode {0} in a context that does not allow it (e.g. during query deserialization). The most common case of recording a dependency on a DepNode `foo` is when the corresponding query `foo` is invoked. Invoking queries is not allowed as part of loading something from the incremental on-disk cache. See <https://github.com/rust-lang/rust/pull/91919>.",
            dep_node));
}panic!(
1390        "Error: trying to record dependency on DepNode {dep_node} in a \
1391         context that does not allow it (e.g. during query deserialization). \
1392         The most common case of recording a dependency on a DepNode `foo` is \
1393         when the corresponding query `foo` is invoked. Invoking queries is not \
1394         allowed as part of loading something from the incremental on-disk cache. \
1395         See <https://github.com/rust-lang/rust/pull/91919>."
1396    )
1397}
1398
1399impl<'tcx> TyCtxt<'tcx> {
1400    /// Return whether this kind always require evaluation.
1401    #[inline(always)]
1402    fn is_eval_always(self, kind: DepKind) -> bool {
1403        self.dep_kind_vtable(kind).is_eval_always
1404    }
1405}