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