Skip to main content

rustc_middle/dep_graph/
graph.rs

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