rustc_query_system/dep_graph/
graph.rs

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