Skip to main content

rustc_middle/dep_graph/
graph.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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