Skip to main content

rustc_middle/dep_graph/
graph.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::marker::PhantomData;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU32, Ordering};
6
7use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_data_structures::profiling::QueryInvocationId;
10use rustc_data_structures::sharded::{self, ShardedHashMap};
11use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
12use rustc_data_structures::sync::{AtomicU64, Lock, is_dyn_thread_safe};
13use rustc_data_structures::unord::UnordMap;
14use rustc_data_structures::{assert_matches, outline};
15use rustc_errors::DiagInner;
16use rustc_index::IndexVec;
17use rustc_macros::{Decodable, Encodable};
18use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
19use rustc_session::Session;
20use tracing::{debug, 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::StableHashingContext;
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),
        }
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for QuerySideEffect {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    QuerySideEffect::Diagnostic(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 {
                QuerySideEffect::Diagnostic(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };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}
49#[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)]
50pub struct DepGraph {
51    data: Option<Arc<DepGraphData>>,
52
53    /// This field is used for assigning DepNodeIndices when running in
54    /// non-incremental mode. Even in non-incremental mode we make sure that
55    /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
56    /// ID is used for self-profiling.
57    virtual_dep_node_index: Arc<AtomicU32>,
58}
59
60impl ::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! {
61    pub struct DepNodeIndex {}
62}
63
64// We store a large collection of these in `prev_index_to_index` during
65// non-full incremental builds, and want to ensure that the element size
66// doesn't inadvertently increase.
67const _: [(); 4] = [(); ::std::mem::size_of::<Option<DepNodeIndex>>()];rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
68
69impl DepNodeIndex {
70    const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
71    pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
72}
73
74impl From<DepNodeIndex> for QueryInvocationId {
75    #[inline(always)]
76    fn from(dep_node_index: DepNodeIndex) -> Self {
77        QueryInvocationId(dep_node_index.as_u32())
78    }
79}
80
81pub(crate) struct MarkFrame<'a> {
82    index: SerializedDepNodeIndex,
83    parent: Option<&'a MarkFrame<'a>>,
84}
85
86#[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)]
87pub(super) enum DepNodeColor {
88    Green(DepNodeIndex),
89    Red,
90    Unknown,
91}
92
93pub struct DepGraphData {
94    /// The new encoding of the dependency graph, optimized for red/green
95    /// tracking. The `current` field is the dependency graph of only the
96    /// current compilation session: We don't merge the previous dep-graph into
97    /// current one anymore, but we do reference shared data to save space.
98    current: CurrentDepGraph,
99
100    /// The dep-graph from the previous compilation session. It contains all
101    /// nodes and edges as well as all fingerprints of nodes that have them.
102    previous: Arc<SerializedDepGraph>,
103
104    colors: DepNodeColorMap,
105
106    /// When we load, there may be `.o` files, cached MIR, or other such
107    /// things available to us. If we find that they are not dirty, we
108    /// load the path to the file storing those work-products here into
109    /// this map. We can later look for and extract that data.
110    previous_work_products: WorkProductMap,
111
112    dep_node_debug: Lock<FxHashMap<DepNode, String>>,
113
114    /// Used by incremental compilation tests to assert that
115    /// a particular query result was decoded from disk
116    /// (not just marked green)
117    debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
118}
119
120pub fn hash_result<R>(hcx: &mut StableHashingContext<'_>, result: &R) -> Fingerprint
121where
122    R: for<'a> HashStable<StableHashingContext<'a>>,
123{
124    let mut stable_hasher = StableHasher::new();
125    result.hash_stable(hcx, &mut stable_hasher);
126    stable_hasher.finish()
127}
128
129impl DepGraph {
130    pub fn new(
131        session: &Session,
132        prev_graph: Arc<SerializedDepGraph>,
133        prev_work_products: WorkProductMap,
134        encoder: FileEncoder,
135    ) -> DepGraph {
136        let prev_graph_node_count = prev_graph.node_count();
137
138        let current =
139            CurrentDepGraph::new(session, prev_graph_node_count, encoder, Arc::clone(&prev_graph));
140
141        let colors = DepNodeColorMap::new(prev_graph_node_count);
142
143        // Instantiate a node with zero dependencies only once for anonymous queries.
144        let _green_node_index = current.alloc_new_node(
145            DepNode { kind: DepKind::AnonZeroDeps, key_fingerprint: current.anon_id_seed.into() },
146            EdgesVec::new(),
147            Fingerprint::ZERO,
148        );
149        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);
150
151        // Create a single always-red node, with no dependencies of its own.
152        // Other nodes can use the always-red node as a fake dependency, to
153        // ensure that their dependency list will never be all-green.
154        let red_node_index = current.alloc_new_node(
155            DepNode { kind: DepKind::Red, key_fingerprint: Fingerprint::ZERO.into() },
156            EdgesVec::new(),
157            Fingerprint::ZERO,
158        );
159        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);
160        if prev_graph_node_count > 0 {
161            colors.insert_red(SerializedDepNodeIndex::from_u32(
162                DepNodeIndex::FOREVER_RED_NODE.as_u32(),
163            ));
164        }
165
166        DepGraph {
167            data: Some(Arc::new(DepGraphData {
168                previous_work_products: prev_work_products,
169                dep_node_debug: Default::default(),
170                current,
171                previous: prev_graph,
172                colors,
173                debug_loaded_from_disk: Default::default(),
174            })),
175            virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
176        }
177    }
178
179    pub fn new_disabled() -> DepGraph {
180        DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
181    }
182
183    #[inline]
184    pub fn data(&self) -> Option<&DepGraphData> {
185        self.data.as_deref()
186    }
187
188    /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
189    #[inline]
190    pub fn is_fully_enabled(&self) -> bool {
191        self.data.is_some()
192    }
193
194    pub fn with_retained_dep_graph(&self, f: impl Fn(&RetainedDepGraph)) {
195        if let Some(data) = &self.data {
196            data.current.encoder.with_retained_dep_graph(f)
197        }
198    }
199
200    pub fn assert_ignored(&self) {
201        if let Some(..) = self.data {
202            read_deps(|task_deps| {
203                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!(
204                    task_deps,
205                    TaskDepsRef::Ignore,
206                    "expected no task dependency tracking"
207                );
208            })
209        }
210    }
211
212    pub fn with_ignore<OP, R>(&self, op: OP) -> R
213    where
214        OP: FnOnce() -> R,
215    {
216        with_deps(TaskDepsRef::Ignore, op)
217    }
218
219    /// Used to wrap the deserialization of a query result from disk,
220    /// This method enforces that no new `DepNodes` are created during
221    /// query result deserialization.
222    ///
223    /// Enforcing this makes the query dep graph simpler - all nodes
224    /// must be created during the query execution, and should be
225    /// created from inside the 'body' of a query (the implementation
226    /// provided by a particular compiler crate).
227    ///
228    /// Consider the case of three queries `A`, `B`, and `C`, where
229    /// `A` invokes `B` and `B` invokes `C`:
230    ///
231    /// `A -> B -> C`
232    ///
233    /// Suppose that decoding the result of query `B` required re-computing
234    /// the query `C`. If we did not create a fresh `TaskDeps` when
235    /// decoding `B`, we would still be using the `TaskDeps` for query `A`
236    /// (if we needed to re-execute `A`). This would cause us to create
237    /// a new edge `A -> C`. If this edge did not previously
238    /// exist in the `DepGraph`, then we could end up with a different
239    /// `DepGraph` at the end of compilation, even if there were no
240    /// meaningful changes to the overall program (e.g. a newline was added).
241    /// In addition, this edge might cause a subsequent compilation run
242    /// to try to force `C` before marking other necessary nodes green. If
243    /// `C` did not exist in the new compilation session, then we could
244    /// get an ICE. Normally, we would have tried (and failed) to mark
245    /// some other query green (e.g. `item_children`) which was used
246    /// to obtain `C`, which would prevent us from ever trying to force
247    /// a nonexistent `D`.
248    ///
249    /// It might be possible to enforce that all `DepNode`s read during
250    /// deserialization already exist in the previous `DepGraph`. In
251    /// the above example, we would invoke `D` during the deserialization
252    /// of `B`. Since we correctly create a new `TaskDeps` from the decoding
253    /// of `B`, this would result in an edge `B -> D`. If that edge already
254    /// existed (with the same `DepPathHash`es), then it should be correct
255    /// to allow the invocation of the query to proceed during deserialization
256    /// of a query result. We would merely assert that the dep-graph fragment
257    /// that would have been added by invoking `C` while decoding `B`
258    /// is equivalent to the dep-graph fragment that we already instantiated for B
259    /// (at the point where we successfully marked B as green).
260    ///
261    /// However, this would require additional complexity
262    /// in the query infrastructure, and is not currently needed by the
263    /// decoding of any query results. Should the need arise in the future,
264    /// we should consider extending the query system with this functionality.
265    pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
266    where
267        OP: FnOnce() -> R,
268    {
269        with_deps(TaskDepsRef::Forbid, op)
270    }
271
272    #[inline(always)]
273    pub fn with_task<'tcx, A: Debug, R>(
274        &self,
275        dep_node: DepNode,
276        tcx: TyCtxt<'tcx>,
277        task_arg: A,
278        task_fn: fn(tcx: TyCtxt<'tcx>, task_arg: A) -> R,
279        hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
280    ) -> (R, DepNodeIndex) {
281        match self.data() {
282            Some(data) => data.with_task(dep_node, tcx, task_arg, task_fn, hash_result),
283            None => (task_fn(tcx, task_arg), self.next_virtual_depnode_index()),
284        }
285    }
286
287    pub fn with_anon_task<'tcx, OP, R>(
288        &self,
289        cx: TyCtxt<'tcx>,
290        dep_kind: DepKind,
291        op: OP,
292    ) -> (R, DepNodeIndex)
293    where
294        OP: FnOnce() -> R,
295    {
296        match self.data() {
297            Some(data) => {
298                let (result, index) = data.with_anon_task_inner(cx, dep_kind, op);
299                self.read_index(index);
300                (result, index)
301            }
302            None => (op(), self.next_virtual_depnode_index()),
303        }
304    }
305}
306
307impl DepGraphData {
308    /// Starts a new dep-graph task. Dep-graph tasks are specified
309    /// using a free function (`task`) and **not** a closure -- this
310    /// is intentional because we want to exercise tight control over
311    /// what state they have access to. In particular, we want to
312    /// prevent implicit 'leaks' of tracked state into the task (which
313    /// could then be read without generating correct edges in the
314    /// dep-graph -- see the [rustc dev guide] for more details on
315    /// the dep-graph).
316    ///
317    /// Therefore, the task function takes a `TyCtxt`, plus exactly one
318    /// additional argument, `task_arg`. The additional argument type can be
319    /// `()` if no argument is needed, or a tuple if multiple arguments are
320    /// needed.
321    ///
322    /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/queries/incremental-compilation.html
323    #[inline(always)]
324    pub fn with_task<'tcx, A: Debug, R>(
325        &self,
326        dep_node: DepNode,
327        tcx: TyCtxt<'tcx>,
328        task_arg: A,
329        task_fn: fn(tcx: TyCtxt<'tcx>, task_arg: A) -> R,
330        hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
331    ) -> (R, DepNodeIndex) {
332        // If the following assertion triggers, it can have two reasons:
333        // 1. Something is wrong with DepNode creation, either here or
334        //    in `DepGraph::try_mark_green()`.
335        // 2. Two distinct query keys get mapped to the same `DepNode`
336        //    (see for example #48923).
337        self.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
338            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("forcing query with already existing `DepNode`\n- query-key: {0:?}\n- dep-node: {1:?}",
                task_arg, dep_node))
    })format!(
339                "forcing query with already existing `DepNode`\n\
340                 - query-key: {task_arg:?}\n\
341                 - dep-node: {dep_node:?}"
342            )
343        });
344
345        let with_deps = |task_deps| with_deps(task_deps, || task_fn(tcx, task_arg));
346        let (result, edges) = if tcx.is_eval_always(dep_node.kind) {
347            (with_deps(TaskDepsRef::EvalAlways), EdgesVec::new())
348        } else {
349            let task_deps = Lock::new(TaskDeps::new(
350                #[cfg(debug_assertions)]
351                Some(dep_node),
352                0,
353            ));
354            (with_deps(TaskDepsRef::Allow(&task_deps)), task_deps.into_inner().reads)
355        };
356
357        let dep_node_index =
358            self.hash_result_and_alloc_node(tcx, dep_node, edges, &result, hash_result);
359
360        (result, dep_node_index)
361    }
362
363    /// Executes something within an "anonymous" task, that is, a task the
364    /// `DepNode` of which is determined by the list of inputs it read from.
365    ///
366    /// NOTE: this does not actually count as a read of the DepNode here.
367    /// Using the result of this task without reading the DepNode will result
368    /// in untracked dependencies which may lead to ICEs as nodes are
369    /// incorrectly marked green.
370    ///
371    /// FIXME: This could perhaps return a `WithDepNode` to ensure that the
372    /// user of this function actually performs the read; we'll have to see
373    /// how to make that work with `anon` in `execute_job_incr`, though.
374    pub fn with_anon_task_inner<'tcx, OP, R>(
375        &self,
376        cx: TyCtxt<'tcx>,
377        dep_kind: DepKind,
378        op: OP,
379    ) -> (R, DepNodeIndex)
380    where
381        OP: FnOnce() -> R,
382    {
383        if true {
    if !!cx.is_eval_always(dep_kind) {
        ::core::panicking::panic("assertion failed: !cx.is_eval_always(dep_kind)")
    };
};debug_assert!(!cx.is_eval_always(dep_kind));
384
385        // Large numbers of reads are common enough here that pre-sizing `read_set`
386        // to 128 actually helps perf on some benchmarks.
387        let task_deps = Lock::new(TaskDeps::new(
388            #[cfg(debug_assertions)]
389            None,
390            128,
391        ));
392        let result = with_deps(TaskDepsRef::Allow(&task_deps), op);
393        let task_deps = task_deps.into_inner();
394        let reads = task_deps.reads;
395
396        let dep_node_index = match reads.len() {
397            0 => {
398                // Because the dep-node id of anon nodes is computed from the sets of its
399                // dependencies we already know what the ID of this dependency-less node is
400                // going to be (i.e. equal to the precomputed
401                // `SINGLETON_DEPENDENCYLESS_ANON_NODE`). As a consequence we can skip creating
402                // a `StableHasher` and sending the node through interning.
403                DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE
404            }
405            1 => {
406                // When there is only one dependency, don't bother creating a node.
407                reads[0]
408            }
409            _ => {
410                // The dep node indices are hashed here instead of hashing the dep nodes of the
411                // dependencies. These indices may refer to different nodes per session, but this isn't
412                // a problem here because we that ensure the final dep node hash is per session only by
413                // combining it with the per session random number `anon_id_seed`. This hash only need
414                // to map the dependencies to a single value on a per session basis.
415                let mut hasher = StableHasher::new();
416                reads.hash(&mut hasher);
417
418                let target_dep_node = DepNode {
419                    kind: dep_kind,
420                    // Fingerprint::combine() is faster than sending Fingerprint
421                    // through the StableHasher (at least as long as StableHasher
422                    // is so slow).
423                    key_fingerprint: self.current.anon_id_seed.combine(hasher.finish()).into(),
424                };
425
426                // The DepNodes generated by the process above are not unique. 2 queries could
427                // have exactly the same dependencies. However, deserialization does not handle
428                // duplicated nodes, so we do the deduplication here directly.
429                //
430                // As anonymous nodes are a small quantity compared to the full dep-graph, the
431                // memory impact of this `anon_node_to_index` map remains tolerable, and helps
432                // us avoid useless growth of the graph with almost-equivalent nodes.
433                self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
434                    self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
435                })
436            }
437        };
438
439        (result, dep_node_index)
440    }
441
442    /// Intern the new `DepNode` with the dependencies up-to-now.
443    fn hash_result_and_alloc_node<'tcx, R>(
444        &self,
445        tcx: TyCtxt<'tcx>,
446        node: DepNode,
447        edges: EdgesVec,
448        result: &R,
449        hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
450    ) -> DepNodeIndex {
451        let hashing_timer = tcx.prof.incr_result_hashing();
452        let current_fingerprint = hash_result.map(|hash_result| {
453            tcx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
454        });
455        let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
456        hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
457        dep_node_index
458    }
459}
460
461impl DepGraph {
462    #[inline]
463    pub fn read_index(&self, dep_node_index: DepNodeIndex) {
464        if let Some(ref data) = self.data {
465            read_deps(|task_deps| {
466                let mut task_deps = match task_deps {
467                    TaskDepsRef::Allow(deps) => deps.lock(),
468                    TaskDepsRef::EvalAlways => {
469                        // We don't need to record dependencies of eval_always
470                        // queries. They are re-evaluated unconditionally anyway.
471                        return;
472                    }
473                    TaskDepsRef::Ignore => return,
474                    TaskDepsRef::Forbid => {
475                        // Reading is forbidden in this context. ICE with a useful error message.
476                        panic_on_forbidden_read(data, dep_node_index)
477                    }
478                };
479                let task_deps = &mut *task_deps;
480
481                if truecfg!(debug_assertions) {
482                    data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
483                }
484
485                // Has `dep_node_index` been seen before? Use either a linear scan or a hashset
486                // lookup to determine this. See `TaskDeps::read_set` for details.
487                let new_read = if task_deps.reads.len() <= TaskDeps::LINEAR_SCAN_MAX {
488                    !task_deps.reads.contains(&dep_node_index)
489                } else {
490                    task_deps.read_set.insert(dep_node_index)
491                };
492                if new_read {
493                    task_deps.reads.push(dep_node_index);
494                    if task_deps.reads.len() == TaskDeps::LINEAR_SCAN_MAX + 1 {
495                        // Fill `read_set` with what we have so far. Future lookups will use it.
496                        task_deps.read_set.extend(task_deps.reads.iter().copied());
497                    }
498
499                    #[cfg(debug_assertions)]
500                    {
501                        if let Some(target) = task_deps.node
502                            && let Some(ref forbidden_edge) = data.current.forbidden_edge
503                        {
504                            let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
505                            if forbidden_edge.test(&src, &target) {
506                                {
    ::core::panicking::panic_fmt(format_args!("forbidden edge {0:?} -> {1:?} created",
            src, target));
}panic!("forbidden edge {:?} -> {:?} created", src, target)
507                            }
508                        }
509                    }
510                } else if truecfg!(debug_assertions) {
511                    data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
512                }
513            })
514        }
515    }
516
517    /// This encodes a diagnostic by creating a node with an unique index and associating
518    /// `diagnostic` with it, for use in the next session.
519    #[inline]
520    pub fn record_diagnostic<'tcx>(&self, tcx: TyCtxt<'tcx>, diagnostic: &DiagInner) {
521        if let Some(ref data) = self.data {
522            read_deps(|task_deps| match task_deps {
523                TaskDepsRef::EvalAlways | TaskDepsRef::Ignore => return,
524                TaskDepsRef::Forbid | TaskDepsRef::Allow(..) => {
525                    self.read_index(data.encode_diagnostic(tcx, diagnostic));
526                }
527            })
528        }
529    }
530    /// This forces a diagnostic node green by running its side effect. `prev_index` would
531    /// refer to a node created used `encode_diagnostic` in the previous session.
532    #[inline]
533    pub fn force_diagnostic_node<'tcx>(
534        &self,
535        tcx: TyCtxt<'tcx>,
536        prev_index: SerializedDepNodeIndex,
537    ) {
538        if let Some(ref data) = self.data {
539            data.force_diagnostic_node(tcx, prev_index);
540        }
541    }
542
543    /// Create a node when we force-feed a value into the query cache.
544    /// This is used to remove cycles during type-checking const generic parameters.
545    ///
546    /// As usual in the query system, we consider the current state of the calling query
547    /// only depends on the list of dependencies up to now. As a consequence, the value
548    /// that this query gives us can only depend on those dependencies too. Therefore,
549    /// it is sound to use the current dependency set for the created node.
550    ///
551    /// During replay, the order of the nodes is relevant in the dependency graph.
552    /// So the unchanged replay will mark the caller query before trying to mark this one.
553    /// If there is a change to report, the caller query will be re-executed before this one.
554    ///
555    /// FIXME: If the code is changed enough for this node to be marked before requiring the
556    /// caller's node, we suppose that those changes will be enough to mark this node red and
557    /// force a recomputation using the "normal" way.
558    pub fn with_feed_task<'tcx, R>(
559        &self,
560        node: DepNode,
561        tcx: TyCtxt<'tcx>,
562        result: &R,
563        hash_result: Option<fn(&mut StableHashingContext<'_>, &R) -> Fingerprint>,
564        format_value_fn: fn(&R) -> String,
565    ) -> DepNodeIndex {
566        if let Some(data) = self.data.as_ref() {
567            // The caller query has more dependencies than the node we are creating. We may
568            // encounter a case where this created node is marked as green, but the caller query is
569            // subsequently marked as red or recomputed. In this case, we will end up feeding a
570            // value to an existing node.
571            //
572            // For sanity, we still check that the loaded stable hash and the new one match.
573            if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
574                let dep_node_index = data.colors.current(prev_index);
575                if let Some(dep_node_index) = dep_node_index {
576                    incremental_verify_ich(
577                        tcx,
578                        data,
579                        result,
580                        prev_index,
581                        hash_result,
582                        format_value_fn,
583                    );
584
585                    #[cfg(debug_assertions)]
586                    if hash_result.is_some() {
587                        data.current.record_edge(
588                            dep_node_index,
589                            node,
590                            data.prev_value_fingerprint_of(prev_index),
591                        );
592                    }
593
594                    return dep_node_index;
595                }
596            }
597
598            let mut edges = EdgesVec::new();
599            read_deps(|task_deps| match task_deps {
600                TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()),
601                TaskDepsRef::EvalAlways => {
602                    edges.push(DepNodeIndex::FOREVER_RED_NODE);
603                }
604                TaskDepsRef::Ignore => {}
605                TaskDepsRef::Forbid => {
606                    {
    ::core::panicking::panic_fmt(format_args!("Cannot summarize when dependencies are not recorded."));
}panic!("Cannot summarize when dependencies are not recorded.")
607                }
608            });
609
610            data.hash_result_and_alloc_node(tcx, node, edges, result, hash_result)
611        } else {
612            // Incremental compilation is turned off. We just execute the task
613            // without tracking. We still provide a dep-node index that uniquely
614            // identifies the task so that we have a cheap way of referring to
615            // the query for self-profiling.
616            self.next_virtual_depnode_index()
617        }
618    }
619}
620
621impl DepGraphData {
622    fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
623        &self,
624        sess: &Session,
625        dep_node: &DepNode,
626        msg: impl FnOnce() -> S,
627    ) {
628        if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
629            let color = self.colors.get(prev_index);
630            let ok = match color {
631                DepNodeColor::Unknown => true,
632                DepNodeColor::Red => false,
633                DepNodeColor::Green(..) => sess.threads() > 1, // Other threads may mark this green
634            };
635            if !ok {
636                { ::core::panicking::panic_display(&msg()); }panic!("{}", msg())
637            }
638        } else if let Some(nodes_in_current_session) = &self.current.nodes_in_current_session {
639            outline(|| {
640                let seen = nodes_in_current_session.lock().contains_key(dep_node);
641                if !!seen { { ::core::panicking::panic_display(&msg()); } };assert!(!seen, "{}", msg());
642            });
643        }
644    }
645
646    fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
647        if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
648            self.colors.get(prev_index)
649        } else {
650            // This is a node that did not exist in the previous compilation session.
651            DepNodeColor::Unknown
652        }
653    }
654
655    /// Returns true if the given node has been marked as green during the
656    /// current compilation session. Used in various assertions
657    #[inline]
658    pub fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
659        #[allow(non_exhaustive_omitted_patterns)] match self.colors.get(prev_index) {
    DepNodeColor::Green(_) => true,
    _ => false,
}matches!(self.colors.get(prev_index), DepNodeColor::Green(_))
660    }
661
662    #[inline]
663    pub fn prev_value_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
664        self.previous.value_fingerprint_for_index(prev_index)
665    }
666
667    #[inline]
668    pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> &DepNode {
669        self.previous.index_to_node(prev_index)
670    }
671
672    pub fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
673        self.debug_loaded_from_disk.lock().insert(dep_node);
674    }
675
676    /// This encodes a diagnostic by creating a node with an unique index and associating
677    /// `diagnostic` with it, for use in the next session.
678    #[inline]
679    fn encode_diagnostic<'tcx>(&self, tcx: TyCtxt<'tcx>, diagnostic: &DiagInner) -> DepNodeIndex {
680        // Use `send_new` so we get an unique index, even though the dep node is not.
681        let dep_node_index = self.current.encoder.send_new(
682            DepNode {
683                kind: DepKind::SideEffect,
684                key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
685            },
686            Fingerprint::ZERO,
687            // We want the side effect node to always be red so it will be forced and emit the
688            // diagnostic.
689            std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
690        );
691        let side_effect = QuerySideEffect::Diagnostic(diagnostic.clone());
692        tcx.store_side_effect(dep_node_index, side_effect);
693        dep_node_index
694    }
695
696    /// This forces a diagnostic node green by running its side effect. `prev_index` would
697    /// refer to a node created used `encode_diagnostic` in the previous session.
698    #[inline]
699    fn force_diagnostic_node<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
700        with_deps(TaskDepsRef::Ignore, || {
701            let side_effect = tcx.load_side_effect(prev_index).unwrap();
702
703            match &side_effect {
704                QuerySideEffect::Diagnostic(diagnostic) => {
705                    tcx.dcx().emit_diagnostic(diagnostic.clone());
706                }
707            }
708
709            // Use `send_and_color` as `promote_node_and_deps_to_current` expects all
710            // green dependencies. `send_and_color` will also prevent multiple nodes
711            // being encoded for concurrent calls.
712            let dep_node_index = self.current.encoder.send_and_color(
713                prev_index,
714                &self.colors,
715                DepNode {
716                    kind: DepKind::SideEffect,
717                    key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
718                },
719                Fingerprint::ZERO,
720                std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
721                true,
722            );
723            // This will just overwrite the same value for concurrent calls.
724            tcx.store_side_effect(dep_node_index, side_effect);
725        })
726    }
727
728    fn alloc_and_color_node(
729        &self,
730        key: DepNode,
731        edges: EdgesVec,
732        value_fingerprint: Option<Fingerprint>,
733    ) -> DepNodeIndex {
734        if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
735            // Determine the color and index of the new `DepNode`.
736            let is_green = if let Some(value_fingerprint) = value_fingerprint {
737                if value_fingerprint == self.previous.value_fingerprint_for_index(prev_index) {
738                    // This is a green node: it existed in the previous compilation,
739                    // its query was re-executed, and it has the same result as before.
740                    true
741                } else {
742                    // This is a red node: it existed in the previous compilation, its query
743                    // was re-executed, but it has a different result from before.
744                    false
745                }
746            } else {
747                // This is a red node, effectively: it existed in the previous compilation
748                // session, its query was re-executed, but it doesn't compute a result hash
749                // (i.e. it represents a `no_hash` query), so we have no way of determining
750                // whether or not the result was the same as before.
751                false
752            };
753
754            let value_fingerprint = value_fingerprint.unwrap_or(Fingerprint::ZERO);
755
756            let dep_node_index = self.current.encoder.send_and_color(
757                prev_index,
758                &self.colors,
759                key,
760                value_fingerprint,
761                edges,
762                is_green,
763            );
764
765            self.current.record_node(dep_node_index, key, value_fingerprint);
766
767            dep_node_index
768        } else {
769            self.current.alloc_new_node(key, edges, value_fingerprint.unwrap_or(Fingerprint::ZERO))
770        }
771    }
772
773    fn promote_node_and_deps_to_current(
774        &self,
775        prev_index: SerializedDepNodeIndex,
776    ) -> Option<DepNodeIndex> {
777        self.current.debug_assert_not_in_new_nodes(&self.previous, prev_index);
778
779        let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors);
780
781        #[cfg(debug_assertions)]
782        if let Some(dep_node_index) = dep_node_index {
783            self.current.record_edge(
784                dep_node_index,
785                *self.previous.index_to_node(prev_index),
786                self.previous.value_fingerprint_for_index(prev_index),
787            );
788        }
789
790        dep_node_index
791    }
792}
793
794impl DepGraph {
795    /// Checks whether a previous work product exists for `v` and, if
796    /// so, return the path that leads to it. Used to skip doing work.
797    pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
798        self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
799    }
800
801    /// Access the map of work-products created during the cached run. Only
802    /// used during saving of the dep-graph.
803    pub fn previous_work_products(&self) -> &WorkProductMap {
804        &self.data.as_ref().unwrap().previous_work_products
805    }
806
807    pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
808        self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
809    }
810
811    pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool {
812        // We only check if we have a dep node corresponding to the given dep kind.
813        #[allow(rustc::potential_query_instability)]
814        self.data
815            .as_ref()
816            .unwrap()
817            .debug_loaded_from_disk
818            .lock()
819            .iter()
820            .any(|node| node.kind == dep_kind)
821    }
822
823    #[cfg(debug_assertions)]
824    #[inline(always)]
825    pub(crate) fn register_dep_node_debug_str<F>(&self, dep_node: DepNode, debug_str_gen: F)
826    where
827        F: FnOnce() -> String,
828    {
829        // Early queries (e.g., `-Z query-dep-graph` on empty crates) can reach here
830        // before the graph is initialized. Return early to prevent an ICE.
831        let data = match &self.data {
832            Some(d) => d,
833            None => return,
834        };
835        let dep_node_debug = &data.dep_node_debug;
836
837        if dep_node_debug.borrow().contains_key(&dep_node) {
838            return;
839        }
840        let debug_str = self.with_ignore(debug_str_gen);
841        dep_node_debug.borrow_mut().insert(dep_node, debug_str);
842    }
843
844    pub fn dep_node_debug_str(&self, dep_node: DepNode) -> Option<String> {
845        self.data.as_ref()?.dep_node_debug.borrow().get(&dep_node).cloned()
846    }
847
848    fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
849        if let Some(ref data) = self.data {
850            return data.node_color(dep_node);
851        }
852
853        DepNodeColor::Unknown
854    }
855
856    pub fn try_mark_green<'tcx>(
857        &self,
858        tcx: TyCtxt<'tcx>,
859        dep_node: &DepNode,
860    ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
861        self.data().and_then(|data| data.try_mark_green(tcx, dep_node))
862    }
863}
864
865impl DepGraphData {
866    /// Try to mark a node index for the node dep_node.
867    ///
868    /// A node will have an index, when it's already been marked green, or when we can mark it
869    /// green. This function will mark the current task as a reader of the specified node, when
870    /// a node index can be found for that node.
871    pub fn try_mark_green<'tcx>(
872        &self,
873        tcx: TyCtxt<'tcx>,
874        dep_node: &DepNode,
875    ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
876        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));
877
878        // Return None if the dep node didn't exist in the previous session
879        let prev_index = self.previous.node_to_index_opt(dep_node)?;
880
881        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);
882
883        match self.colors.get(prev_index) {
884            DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
885            DepNodeColor::Red => None,
886            DepNodeColor::Unknown => {
887                // This DepNode and the corresponding query invocation existed
888                // in the previous compilation session too, so we can try to
889                // mark it as green by recursively marking all of its
890                // dependencies green.
891                self.try_mark_previous_green(tcx, prev_index, None)
892                    .map(|dep_node_index| (prev_index, dep_node_index))
893            }
894        }
895    }
896
897    #[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_parent_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(897u32),
                                    ::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<()> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let get_dep_dep_node =
                || self.previous.index_to_node(parent_dep_node_index);
            match self.colors.get(parent_dep_node_index) {
                DepNodeColor::Green(_) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:915",
                                            "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(915u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("dependency {0:?} was immediately green",
                                                                        get_dep_dep_node()) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return Some(());
                }
                DepNodeColor::Red => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:923",
                                            "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(923u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("dependency {0:?} was immediately red",
                                                                        get_dep_dep_node()) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return None;
                }
                DepNodeColor::Unknown => {}
            }
            let dep_dep_node = get_dep_dep_node();
            if !tcx.is_eval_always(dep_dep_node.kind) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:934",
                                        "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(934u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("state of dependency {0:?} ({1}) is unknown, trying to mark it green",
                                                                    dep_dep_node, dep_dep_node.key_fingerprint) as
                                                            &dyn Value))])
                            });
                    } else { ; }
                };
                let node_index =
                    self.try_mark_previous_green(tcx, parent_dep_node_index,
                        Some(frame));
                if node_index.is_some() {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:942",
                                            "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(942u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("managed to MARK dependency {0:?} as green",
                                                                        dep_dep_node) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return Some(());
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:948",
                                    "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(948u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("trying to force dependency {0:?}",
                                                                dep_dep_node) as &dyn Value))])
                        });
                } else { ; }
            };
            if !tcx.try_force_from_dep_node(*dep_dep_node,
                        parent_dep_node_index, frame) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:951",
                                        "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(951u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("dependency {0:?} could not be forced",
                                                                    dep_dep_node) as &dyn Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            match self.colors.get(parent_dep_node_index) {
                DepNodeColor::Green(_) => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:957",
                                            "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(957u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("managed to FORCE dependency {0:?} to green",
                                                                        dep_dep_node) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return Some(());
                }
                DepNodeColor::Red => {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:961",
                                            "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(961u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                        ::tracing::__macro_support::Option::Some(&format_args!("dependency {0:?} was red after forcing",
                                                                        dep_dep_node) as &dyn Value))])
                                });
                        } else { ; }
                    };
                    return None;
                }
                DepNodeColor::Unknown => {}
            }
            if let None = tcx.dcx().has_errors_or_delayed_bugs() {
                {
                    ::core::panicking::panic_fmt(format_args!("try_mark_previous_green() - Forcing the DepNode should have set its color"));
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:981",
                                    "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(981u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("dependency {0:?} resulted in compilation error",
                                                                dep_dep_node) as &dyn Value))])
                        });
                } else { ; }
            };
            return None;
        }
    }
}#[instrument(skip(self, tcx, parent_dep_node_index, frame), level = "debug")]
898    fn try_mark_parent_green<'tcx>(
899        &self,
900        tcx: TyCtxt<'tcx>,
901        parent_dep_node_index: SerializedDepNodeIndex,
902        frame: &MarkFrame<'_>,
903    ) -> Option<()> {
904        let get_dep_dep_node = || self.previous.index_to_node(parent_dep_node_index);
905
906        match self.colors.get(parent_dep_node_index) {
907            DepNodeColor::Green(_) => {
908                // This dependency has been marked as green before, we are
909                // still fine and can continue with checking the other
910                // dependencies.
911                //
912                // This path is extremely hot. We don't want to get the
913                // `dep_dep_node` unless it's necessary. Hence the
914                // `get_dep_dep_node` closure.
915                debug!("dependency {:?} was immediately green", get_dep_dep_node());
916                return Some(());
917            }
918            DepNodeColor::Red => {
919                // We found a dependency the value of which has changed
920                // compared to the previous compilation session. We cannot
921                // mark the DepNode as green and also don't need to bother
922                // with checking any of the other dependencies.
923                debug!("dependency {:?} was immediately red", get_dep_dep_node());
924                return None;
925            }
926            DepNodeColor::Unknown => {}
927        }
928
929        let dep_dep_node = get_dep_dep_node();
930
931        // We don't know the state of this dependency. If it isn't
932        // an eval_always node, let's try to mark it green recursively.
933        if !tcx.is_eval_always(dep_dep_node.kind) {
934            debug!(
935                "state of dependency {:?} ({}) is unknown, trying to mark it green",
936                dep_dep_node, dep_dep_node.key_fingerprint,
937            );
938
939            let node_index = self.try_mark_previous_green(tcx, parent_dep_node_index, Some(frame));
940
941            if node_index.is_some() {
942                debug!("managed to MARK dependency {dep_dep_node:?} as green");
943                return Some(());
944            }
945        }
946
947        // We failed to mark it green, so we try to force the query.
948        debug!("trying to force dependency {dep_dep_node:?}");
949        if !tcx.try_force_from_dep_node(*dep_dep_node, parent_dep_node_index, frame) {
950            // The DepNode could not be forced.
951            debug!("dependency {dep_dep_node:?} could not be forced");
952            return None;
953        }
954
955        match self.colors.get(parent_dep_node_index) {
956            DepNodeColor::Green(_) => {
957                debug!("managed to FORCE dependency {dep_dep_node:?} to green");
958                return Some(());
959            }
960            DepNodeColor::Red => {
961                debug!("dependency {dep_dep_node:?} was red after forcing");
962                return None;
963            }
964            DepNodeColor::Unknown => {}
965        }
966
967        if let None = tcx.dcx().has_errors_or_delayed_bugs() {
968            panic!("try_mark_previous_green() - Forcing the DepNode should have set its color")
969        }
970
971        // If the query we just forced has resulted in
972        // some kind of compilation error, we cannot rely on
973        // the dep-node color having been properly updated.
974        // This means that the query system has reached an
975        // invalid state. We let the compiler continue (by
976        // returning `None`) so it can emit error messages
977        // and wind down, but rely on the fact that this
978        // invalid state will not be persisted to the
979        // incremental compilation cache because of
980        // compilation errors being present.
981        debug!("dependency {dep_dep_node:?} resulted in compilation error");
982        return None;
983    }
984
985    /// Try to mark a dep-node which existed in the previous compilation session as green.
986    #[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(986u32),
                                    ::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)")
                };
            };
            let prev_deps =
                self.previous.edge_targets_from(prev_dep_node_index);
            for dep_dep_node_index in prev_deps {
                self.try_mark_parent_green(tcx, dep_dep_node_index, &frame)?;
            }
            let dep_node_index =
                self.promote_node_and_deps_to_current(prev_dep_node_index)?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/dep_graph/graph.rs:1019",
                                    "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(1019u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("successfully marked {0:?} as green",
                                                                self.previous.index_to_node(prev_dep_node_index)) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            Some(dep_node_index)
        }
    }
}#[instrument(skip(self, tcx, prev_dep_node_index, frame), level = "debug")]
987    fn try_mark_previous_green<'tcx>(
988        &self,
989        tcx: TyCtxt<'tcx>,
990        prev_dep_node_index: SerializedDepNodeIndex,
991        frame: Option<&MarkFrame<'_>>,
992    ) -> Option<DepNodeIndex> {
993        let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
994
995        // We never try to mark eval_always nodes as green
996        debug_assert!(!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind));
997
998        let prev_deps = self.previous.edge_targets_from(prev_dep_node_index);
999
1000        for dep_dep_node_index in prev_deps {
1001            self.try_mark_parent_green(tcx, dep_dep_node_index, &frame)?;
1002        }
1003
1004        // If we got here without hitting a `return` that means that all
1005        // dependencies of this DepNode could be marked as green. Therefore we
1006        // can also mark this DepNode as green.
1007
1008        // There may be multiple threads trying to mark the same dep node green concurrently
1009
1010        // We allocating an entry for the node in the current dependency graph and
1011        // adding all the appropriate edges imported from the previous graph.
1012        //
1013        // `no_hash` nodes may fail this promotion due to already being conservatively colored red.
1014        let dep_node_index = self.promote_node_and_deps_to_current(prev_dep_node_index)?;
1015
1016        // ... and finally storing a "Green" entry in the color map.
1017        // Multiple threads can all write the same color here
1018
1019        debug!(
1020            "successfully marked {:?} as green",
1021            self.previous.index_to_node(prev_dep_node_index)
1022        );
1023        Some(dep_node_index)
1024    }
1025}
1026
1027impl DepGraph {
1028    /// Returns true if the given node has been marked as red during the
1029    /// current compilation session. Used in various assertions
1030    pub fn is_red(&self, dep_node: &DepNode) -> bool {
1031        #[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
    DepNodeColor::Red => true,
    _ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Red)
1032    }
1033
1034    /// Returns true if the given node has been marked as green during the
1035    /// current compilation session. Used in various assertions
1036    pub fn is_green(&self, dep_node: &DepNode) -> bool {
1037        #[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
    DepNodeColor::Green(_) => true,
    _ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Green(_))
1038    }
1039
1040    pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
1041        &self,
1042        sess: &Session,
1043        dep_node: &DepNode,
1044        msg: impl FnOnce() -> S,
1045    ) {
1046        if let Some(data) = &self.data {
1047            data.assert_dep_node_not_yet_allocated_in_current_session(sess, dep_node, msg)
1048        }
1049    }
1050
1051    /// This method loads all on-disk cacheable query results into memory, so
1052    /// they can be written out to the new cache file again. Most query results
1053    /// will already be in memory but in the case where we marked something as
1054    /// green but then did not need the value, that value will never have been
1055    /// loaded from disk.
1056    ///
1057    /// This method will only load queries that will end up in the disk cache.
1058    /// Other queries will not be executed.
1059    pub fn exec_cache_promotions<'tcx>(&self, tcx: TyCtxt<'tcx>) {
1060        let _prof_timer = tcx.prof.generic_activity("incr_comp_query_cache_promotion");
1061
1062        let data = self.data.as_ref().unwrap();
1063        for prev_index in data.colors.values.indices() {
1064            match data.colors.get(prev_index) {
1065                DepNodeColor::Green(_) => {
1066                    let dep_node = data.previous.index_to_node(prev_index);
1067                    if let Some(promote_fn) =
1068                        tcx.dep_kind_vtable(dep_node.kind).promote_from_disk_fn
1069                    {
1070                        promote_fn(tcx, *dep_node)
1071                    };
1072                }
1073                DepNodeColor::Unknown | DepNodeColor::Red => {
1074                    // We can skip red nodes because a node can only be marked
1075                    // as red if the query result was recomputed and thus is
1076                    // already in memory.
1077                }
1078            }
1079        }
1080    }
1081
1082    pub fn finish_encoding(&self) -> FileEncodeResult {
1083        if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1084    }
1085
1086    pub fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1087        if true {
    if !self.data.is_none() {
        ::core::panicking::panic("assertion failed: self.data.is_none()")
    };
};debug_assert!(self.data.is_none());
1088        let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1089        DepNodeIndex::from_u32(index)
1090    }
1091}
1092
1093/// A "work product" is an intermediate result that we save into the
1094/// incremental directory for later re-use. The primary example are
1095/// the object files that we save for each partition at code
1096/// generation time.
1097///
1098/// Each work product is associated with a dep-node, representing the
1099/// process that produced the work-product. If that dep-node is found
1100/// to be dirty when we load up, then we will delete the work-product
1101/// at load time. If the work-product is found to be clean, then we
1102/// will keep a record in the `previous_work_products` list.
1103///
1104/// In addition, work products have an associated hash. This hash is
1105/// an extra hash that can be used to decide if the work-product from
1106/// a previous compilation can be re-used (in addition to the dirty
1107/// edges check).
1108///
1109/// As the primary example, consider the object files we generate for
1110/// each partition. In the first run, we create partitions based on
1111/// the symbols that need to be compiled. For each partition P, we
1112/// hash the symbols in P and create a `WorkProduct` record associated
1113/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1114/// in P.
1115///
1116/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1117/// judged to be clean (which means none of the things we read to
1118/// generate the partition were found to be dirty), it will be loaded
1119/// into previous work products. We will then regenerate the set of
1120/// symbols in the partition P and hash them (note that new symbols
1121/// may be added -- for example, new monomorphizations -- even if
1122/// nothing in P changed!). We will compare that hash against the
1123/// previous hash. If it matches up, we can reuse the object file.
1124#[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)]
1125pub struct WorkProduct {
1126    pub cgu_name: String,
1127    /// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1128    /// saved file and the key is some identifier for the type of file being saved.
1129    ///
1130    /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1131    /// the object file's path, and "dwo" to the dwarf object file's path.
1132    pub saved_files: UnordMap<String, String>,
1133}
1134
1135pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
1136
1137// Index type for `DepNodeData`'s edges.
1138impl ::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! {
1139    struct EdgeIndex {}
1140}
1141
1142/// `CurrentDepGraph` stores the dependency graph for the current session. It
1143/// will be populated as we run queries or tasks. We never remove nodes from the
1144/// graph: they are only added.
1145///
1146/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1147/// in memory. This is important, because these graph structures are some of the
1148/// largest in the compiler.
1149///
1150/// For this reason, we avoid storing `DepNode`s more than once as map
1151/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1152/// graph, and we map nodes in the previous graph to indices via a two-step
1153/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1154/// and the `prev_index_to_index` vector (which is more compact and faster than
1155/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1156///
1157/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1158/// and `prev_index_to_index` fields are locked separately. Operations that take
1159/// a `DepNodeIndex` typically just access the `data` field.
1160///
1161/// We only need to manipulate at most two locks simultaneously:
1162/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1163/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1164/// first, and `data` second.
1165pub(super) struct CurrentDepGraph {
1166    encoder: GraphEncoder,
1167    anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
1168
1169    /// This is used to verify that value fingerprints do not change between the
1170    /// creation of a node and its recomputation.
1171    #[cfg(debug_assertions)]
1172    value_fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
1173
1174    /// Used to trap when a specific edge is added to the graph.
1175    /// This is used for debug purposes and is only active with `debug_assertions`.
1176    #[cfg(debug_assertions)]
1177    forbidden_edge: Option<EdgeFilter>,
1178
1179    /// Used to verify the absence of hash collisions among DepNodes.
1180    /// This field is only `Some` if the `-Z incremental_verify_ich` option is present
1181    /// or if `debug_assertions` are enabled.
1182    ///
1183    /// The map contains all DepNodes that have been allocated in the current session so far.
1184    nodes_in_current_session: Option<Lock<FxHashMap<DepNode, DepNodeIndex>>>,
1185
1186    /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1187    /// their edges. This has the beneficial side-effect that multiple anonymous
1188    /// nodes can be coalesced into one without changing the semantics of the
1189    /// dependency graph. However, the merging of nodes can lead to a subtle
1190    /// problem during red-green marking: The color of an anonymous node from
1191    /// the current session might "shadow" the color of the node with the same
1192    /// ID from the previous session. In order to side-step this problem, we make
1193    /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1194    /// This is implemented by mixing a session-key into the ID fingerprint of
1195    /// each anon node. The session-key is a hash of the number of previous sessions.
1196    anon_id_seed: Fingerprint,
1197
1198    /// These are simple counters that are for profiling and
1199    /// debugging and only active with `debug_assertions`.
1200    pub(super) total_read_count: AtomicU64,
1201    pub(super) total_duplicate_read_count: AtomicU64,
1202}
1203
1204impl CurrentDepGraph {
1205    fn new(
1206        session: &Session,
1207        prev_graph_node_count: usize,
1208        encoder: FileEncoder,
1209        previous: Arc<SerializedDepGraph>,
1210    ) -> Self {
1211        let mut stable_hasher = StableHasher::new();
1212        previous.session_count().hash(&mut stable_hasher);
1213        let anon_id_seed = stable_hasher.finish();
1214
1215        #[cfg(debug_assertions)]
1216        let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1217            Ok(s) => match EdgeFilter::new(&s) {
1218                Ok(f) => Some(f),
1219                Err(err) => {
    ::core::panicking::panic_fmt(format_args!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {0}",
            err));
}panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1220            },
1221            Err(_) => None,
1222        };
1223
1224        let new_node_count_estimate = 102 * prev_graph_node_count / 100 + 200;
1225
1226        let new_node_dbg =
1227            session.opts.unstable_opts.incremental_verify_ich || truecfg!(debug_assertions);
1228
1229        CurrentDepGraph {
1230            encoder: GraphEncoder::new(session, encoder, prev_graph_node_count, previous),
1231            anon_node_to_index: ShardedHashMap::with_capacity(
1232                // FIXME: The count estimate is off as anon nodes are only a portion of the nodes.
1233                new_node_count_estimate / sharded::shards(),
1234            ),
1235            anon_id_seed,
1236            #[cfg(debug_assertions)]
1237            forbidden_edge,
1238            #[cfg(debug_assertions)]
1239            value_fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1240            nodes_in_current_session: new_node_dbg.then(|| {
1241                Lock::new(FxHashMap::with_capacity_and_hasher(
1242                    new_node_count_estimate,
1243                    Default::default(),
1244                ))
1245            }),
1246            total_read_count: AtomicU64::new(0),
1247            total_duplicate_read_count: AtomicU64::new(0),
1248        }
1249    }
1250
1251    #[cfg(debug_assertions)]
1252    fn record_edge(
1253        &self,
1254        dep_node_index: DepNodeIndex,
1255        key: DepNode,
1256        value_fingerprint: Fingerprint,
1257    ) {
1258        if let Some(forbidden_edge) = &self.forbidden_edge {
1259            forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1260        }
1261        let prior_value_fingerprint = *self
1262            .value_fingerprints
1263            .lock()
1264            .get_or_insert_with(dep_node_index, || value_fingerprint);
1265        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:?}");
1266    }
1267
1268    #[inline(always)]
1269    fn record_node(
1270        &self,
1271        dep_node_index: DepNodeIndex,
1272        key: DepNode,
1273        _value_fingerprint: Fingerprint,
1274    ) {
1275        #[cfg(debug_assertions)]
1276        self.record_edge(dep_node_index, key, _value_fingerprint);
1277
1278        if let Some(ref nodes_in_current_session) = self.nodes_in_current_session {
1279            outline(|| {
1280                if nodes_in_current_session.lock().insert(key, dep_node_index).is_some() {
1281                    {
    ::core::panicking::panic_fmt(format_args!("Found duplicate dep-node {0:?}",
            key));
};panic!("Found duplicate dep-node {key:?}");
1282                }
1283            });
1284        }
1285    }
1286
1287    /// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1288    /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1289    #[inline(always)]
1290    fn alloc_new_node(
1291        &self,
1292        key: DepNode,
1293        edges: EdgesVec,
1294        value_fingerprint: Fingerprint,
1295    ) -> DepNodeIndex {
1296        let dep_node_index = self.encoder.send_new(key, value_fingerprint, edges);
1297
1298        self.record_node(dep_node_index, key, value_fingerprint);
1299
1300        dep_node_index
1301    }
1302
1303    #[inline]
1304    fn debug_assert_not_in_new_nodes(
1305        &self,
1306        prev_graph: &SerializedDepGraph,
1307        prev_index: SerializedDepNodeIndex,
1308    ) {
1309        if !is_dyn_thread_safe()
1310            && let Some(ref nodes_in_current_session) = self.nodes_in_current_session
1311        {
1312            if true {
    if !!nodes_in_current_session.lock().contains_key(&prev_graph.index_to_node(prev_index))
        {
        {
            ::core::panicking::panic_fmt(format_args!("node from previous graph present in new node collection"));
        }
    };
};debug_assert!(
1313                !nodes_in_current_session
1314                    .lock()
1315                    .contains_key(&prev_graph.index_to_node(prev_index)),
1316                "node from previous graph present in new node collection"
1317            );
1318        }
1319    }
1320}
1321
1322#[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)]
1323pub enum TaskDepsRef<'a> {
1324    /// New dependencies can be added to the
1325    /// `TaskDeps`. This is used when executing a 'normal' query
1326    /// (no `eval_always` modifier)
1327    Allow(&'a Lock<TaskDeps>),
1328    /// This is used when executing an `eval_always` query. We don't
1329    /// need to track dependencies for a query that's always
1330    /// re-executed -- but we need to know that this is an `eval_always`
1331    /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1332    /// when directly feeding other queries.
1333    EvalAlways,
1334    /// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1335    Ignore,
1336    /// Any attempt to add new dependencies will cause a panic.
1337    /// This is used when decoding a query result from disk,
1338    /// to ensure that the decoding process doesn't itself
1339    /// require the execution of any queries.
1340    Forbid,
1341}
1342
1343#[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_field4_finish(f, "TaskDeps",
            "node", &self.node, "reads", &self.reads, "read_set",
            &self.read_set, "phantom_data", &&self.phantom_data)
    }
}Debug)]
1344pub struct TaskDeps {
1345    #[cfg(debug_assertions)]
1346    node: Option<DepNode>,
1347
1348    /// A vector of `DepNodeIndex`, basically.
1349    reads: EdgesVec,
1350
1351    /// When adding new edges to `reads` in `DepGraph::read_index` we need to determine if the edge
1352    /// has been seen before. If the number of elements in `reads` is small, we just do a linear
1353    /// scan. If the number is higher, a hashset has better perf. This field is that hashset. It's
1354    /// only used if the number of elements in `reads` exceeds `LINEAR_SCAN_MAX`.
1355    read_set: FxHashSet<DepNodeIndex>,
1356
1357    phantom_data: PhantomData<DepNode>,
1358}
1359
1360impl TaskDeps {
1361    /// See `TaskDeps::read_set` above.
1362    const LINEAR_SCAN_MAX: usize = 16;
1363
1364    #[inline]
1365    fn new(#[cfg(debug_assertions)] node: Option<DepNode>, read_set_capacity: usize) -> Self {
1366        TaskDeps {
1367            #[cfg(debug_assertions)]
1368            node,
1369            reads: EdgesVec::new(),
1370            read_set: FxHashSet::with_capacity_and_hasher(read_set_capacity, Default::default()),
1371            phantom_data: PhantomData,
1372        }
1373    }
1374}
1375
1376// A data structure that stores Option<DepNodeColor> values as a contiguous
1377// array, using one u32 per entry.
1378pub(super) struct DepNodeColorMap {
1379    values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1380}
1381
1382// All values below `COMPRESSED_RED` are green.
1383const COMPRESSED_RED: u32 = u32::MAX - 1;
1384const COMPRESSED_UNKNOWN: u32 = u32::MAX;
1385
1386impl DepNodeColorMap {
1387    fn new(size: usize) -> DepNodeColorMap {
1388        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);
1389        DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1390    }
1391
1392    #[inline]
1393    pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1394        let value = self.values[index].load(Ordering::Relaxed);
1395        if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1396    }
1397
1398    /// This tries to atomically mark a node green and assign `index` as the new
1399    /// index if `green` is true, otherwise it will try to atomicaly mark it red.
1400    ///
1401    /// This returns `Ok` if `index` gets assigned or the node is marked red, otherwise it returns
1402    /// the already allocated index in `Err` if it is green already. If it was already
1403    /// red, `Err(None)` is returned.
1404    #[inline(always)]
1405    pub(super) fn try_mark(
1406        &self,
1407        prev_index: SerializedDepNodeIndex,
1408        index: DepNodeIndex,
1409        green: bool,
1410    ) -> Result<(), Option<DepNodeIndex>> {
1411        let value = &self.values[prev_index];
1412        match value.compare_exchange(
1413            COMPRESSED_UNKNOWN,
1414            if green { index.as_u32() } else { COMPRESSED_RED },
1415            Ordering::Relaxed,
1416            Ordering::Relaxed,
1417        ) {
1418            Ok(_) => Ok(()),
1419            Err(v) => Err(if v == COMPRESSED_RED { None } else { Some(DepNodeIndex::from_u32(v)) }),
1420        }
1421    }
1422
1423    #[inline]
1424    pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1425        let value = self.values[index].load(Ordering::Acquire);
1426        // Green is by far the most common case. Check for that first so we can succeed with a
1427        // single comparison.
1428        if value < COMPRESSED_RED {
1429            DepNodeColor::Green(DepNodeIndex::from_u32(value))
1430        } else if value == COMPRESSED_RED {
1431            DepNodeColor::Red
1432        } else {
1433            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);
1434            DepNodeColor::Unknown
1435        }
1436    }
1437
1438    #[inline]
1439    pub(super) fn insert_red(&self, index: SerializedDepNodeIndex) {
1440        let value = self.values[index].swap(COMPRESSED_RED, Ordering::Release);
1441        // Sanity check for duplicate nodes
1442        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::Some(format_args!("tried to color an already colored node as red")));
        }
    }
};assert_eq!(value, COMPRESSED_UNKNOWN, "tried to color an already colored node as red");
1443    }
1444}
1445
1446#[inline(never)]
1447#[cold]
1448pub(crate) fn print_markframe_trace(graph: &DepGraph, frame: &MarkFrame<'_>) {
1449    let data = graph.data.as_ref().unwrap();
1450
1451    {
    ::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");
1452    { ::std::io::_eprint(format_args!("try_mark_green dep node stack:\n")); };eprintln!("try_mark_green dep node stack:");
1453
1454    let mut i = 0;
1455    let mut current = Some(frame);
1456    while let Some(frame) = current {
1457        let node = data.previous.index_to_node(frame.index);
1458        { ::std::io::_eprint(format_args!("#{0} {1:?}\n", i, node)); };eprintln!("#{i} {node:?}");
1459        current = frame.parent;
1460        i += 1;
1461    }
1462
1463    {
    ::std::io::_eprint(format_args!("end of try_mark_green dep node stack\n"));
};eprintln!("end of try_mark_green dep node stack");
1464}
1465
1466#[cold]
1467#[inline(never)]
1468fn panic_on_forbidden_read(data: &DepGraphData, dep_node_index: DepNodeIndex) -> ! {
1469    // We have to do an expensive reverse-lookup of the DepNode that
1470    // corresponds to `dep_node_index`, but that's OK since we are about
1471    // to ICE anyway.
1472    let mut dep_node = None;
1473
1474    // First try to find the dep node among those that already existed in the
1475    // previous session and has been marked green
1476    for prev_index in data.colors.values.indices() {
1477        if data.colors.current(prev_index) == Some(dep_node_index) {
1478            dep_node = Some(*data.previous.index_to_node(prev_index));
1479            break;
1480        }
1481    }
1482
1483    if dep_node.is_none()
1484        && let Some(nodes) = &data.current.nodes_in_current_session
1485    {
1486        // Try to find it among the nodes allocated so far in this session
1487        // This is OK, there's only ever one node result possible so this is deterministic.
1488        #[allow(rustc::potential_query_instability)]
1489        if let Some((node, _)) = nodes.lock().iter().find(|&(_, index)| *index == dep_node_index) {
1490            dep_node = Some(*node);
1491        }
1492    }
1493
1494    let dep_node = dep_node.map_or_else(
1495        || ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("with index {0:?}", dep_node_index))
    })format!("with index {:?}", dep_node_index),
1496        |dep_node| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0:?}`", dep_node))
    })format!("`{:?}`", dep_node),
1497    );
1498
1499    {
    ::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!(
1500        "Error: trying to record dependency on DepNode {dep_node} in a \
1501         context that does not allow it (e.g. during query deserialization). \
1502         The most common case of recording a dependency on a DepNode `foo` is \
1503         when the corresponding query `foo` is invoked. Invoking queries is not \
1504         allowed as part of loading something from the incremental on-disk cache. \
1505         See <https://github.com/rust-lang/rust/pull/91919>."
1506    )
1507}
1508
1509impl<'tcx> TyCtxt<'tcx> {
1510    /// Return whether this kind always require evaluation.
1511    #[inline(always)]
1512    fn is_eval_always(self, kind: DepKind) -> bool {
1513        self.dep_kind_vtable(kind).is_eval_always
1514    }
1515
1516    // Interactions with on_disk_cache
1517    fn load_side_effect(
1518        self,
1519        prev_dep_node_index: SerializedDepNodeIndex,
1520    ) -> Option<QuerySideEffect> {
1521        self.query_system
1522            .on_disk_cache
1523            .as_ref()
1524            .and_then(|c| c.load_side_effect(self, prev_dep_node_index))
1525    }
1526
1527    #[inline(never)]
1528    #[cold]
1529    fn store_side_effect(self, dep_node_index: DepNodeIndex, side_effect: QuerySideEffect) {
1530        if let Some(c) = self.query_system.on_disk_cache.as_ref() {
1531            c.store_side_effect(dep_node_index, side_effect)
1532        }
1533    }
1534}