Skip to main content

rustc_middle/dep_graph/
serialized.rs

1//! The data that we will serialize and deserialize.
2//!
3//! Notionally, the dep-graph is a sequence of NodeInfo with the dependencies
4//! specified inline. The total number of nodes and edges are stored as the last
5//! 16 bytes of the file, so we can find them easily at decoding time.
6//!
7//! The serialisation is performed on-demand when each node is emitted. Using this
8//! scheme, we do not need to keep the current graph in memory.
9//!
10//! The deserialization is performed manually, in order to convert from the stored
11//! sequence of NodeInfos to the different arrays in SerializedDepGraph. Since the
12//! node and edge count are stored at the end of the file, all the arrays can be
13//! pre-allocated with the right length.
14//!
15//! The encoding of the dep-graph is generally designed around the fact that fixed-size
16//! reads of encoded data are generally faster than variable-sized reads. Ergo we adopt
17//! essentially the same varint encoding scheme used in the rmeta format; the edge lists
18//! for each node on the graph store a 2-bit integer which is the number of bytes per edge
19//! index in that node's edge list. We effectively ignore that an edge index of 0 could be
20//! encoded with 0 bytes in order to not require 3 bits to store the byte width of the edges.
21//! The overhead of calculating the correct byte width for each edge is mitigated by
22//! computing the max of the edge list once per node instead of per edge.
23//!
24//! When we decode this data, we do not immediately create [`SerializedDepNodeIndex`] and
25//! instead keep the data in its denser serialized form which lets us turn our on-disk size
26//! efficiency directly into a peak memory reduction. When we convert these encoded-in-memory
27//! values into their fully-deserialized type, we use a fixed-size read of the encoded array
28//! then mask off any errant bytes we read. The array of edge index bytes is padded to permit this.
29//!
30//! We also encode and decode the entire rest of each node using [`SerializedNodeHeader`]
31//! to let this encoding and decoding be done in one fixed-size operation. These headers contain
32//! two [`Fingerprint`]s along with the serialized [`DepKind`], and the number of edge indices
33//! in the node and the number of bytes used to encode the edge indices for this node. The
34//! [`DepKind`], number of edges, and bytes per edge are all bit-packed together, if they fit.
35//! If the number of edges in this node does not fit in the bits available in the header, we
36//! store it directly after the header with leb128.
37//!
38//! Dep-graph indices are bulk allocated to threads inside `LocalEncoderState`. Having threads
39//! own these indices helps avoid races when they are conditionally used when marking nodes green.
40//! It also reduces congestion on the shared index count.
41
42use std::cell::RefCell;
43use std::cmp::max;
44use std::hash::{BuildHasher, BuildHasherDefault};
45use std::sync::atomic::Ordering;
46use std::sync::{Arc, OnceLock};
47use std::{iter, mem};
48
49#[cfg(test)]
50mod tests;
51
52use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
53use rustc_data_structures::fx::FxHashMap;
54use rustc_data_structures::hash_table::{Entry, HashTable};
55use rustc_data_structures::outline;
56use rustc_data_structures::profiling::SelfProfilerRef;
57use rustc_data_structures::sync::{AtomicU64, Lock, WorkerLocal, broadcast};
58use rustc_data_structures::unhash::Unhasher;
59use rustc_index::{IndexSlice, IndexVec};
60use rustc_serialize::opaque::mem_encoder::MemEncoder;
61use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder};
62use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
63use rustc_session::Session;
64use tracing::{debug, instrument};
65
66use super::graph::{CurrentDepGraph, DepNodeColorMap, DesiredColor, TrySetColorResult};
67use super::retained::RetainedDepGraph;
68use super::{DepKind, DepNode, DepNodeIndex};
69
70// The maximum value of `SerializedDepNodeIndex` leaves the upper two bits
71// unused so that we can store multiple index types in `CompressedHybridIndex`,
72// and use those bits to encode which index type it contains.
73#[automatically_derived]impl ::core::marker::Copy for SerializedDepNodeIndex {
}
impl SerializedDepNodeIndex {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0x7FFF_FFFF;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0x7FFF_FFFF);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0x7FFF_FFFF as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0x7FFF_FFFF as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0x7FFF_FFFF) {
            ::core::panicking::panic("assertion failed: value <= 0x7FFF_FFFF")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0x7FFF_FFFF) {
            ::core::panicking::panic("assertion failed: value <= 0x7FFF_FFFF")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for SerializedDepNodeIndex {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for SerializedDepNodeIndex {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for SerializedDepNodeIndex {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<SerializedDepNodeIndex> for u32 {
    #[inline]
    fn from(v: SerializedDepNodeIndex) -> u32 { v.as_u32() }
}
impl From<SerializedDepNodeIndex> for usize {
    #[inline]
    fn from(v: SerializedDepNodeIndex) -> usize { v.as_usize() }
}
impl From<usize> for SerializedDepNodeIndex {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for SerializedDepNodeIndex {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for SerializedDepNodeIndex {}
impl ::std::cmp::PartialEq for SerializedDepNodeIndex {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for SerializedDepNodeIndex {}
impl ::std::hash::Hash for SerializedDepNodeIndex {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl<D: ::rustc_serialize::Decoder> ::rustc_serialize::Decodable<D> for
    SerializedDepNodeIndex {
    fn decode(d: &mut D) -> Self { Self::from_u32(d.read_u32()) }
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for
    SerializedDepNodeIndex {
    fn encode(&self, e: &mut E) { e.emit_u32(self.as_u32()); }
}
impl ::std::fmt::Debug for SerializedDepNodeIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
74    #[encodable]
75    #[max = 0x7FFF_FFFF]
76    pub struct SerializedDepNodeIndex {}
77}
78
79impl SerializedDepNodeIndex {
80    /// Converts a current-session dep node index to a "serialized" index,
81    /// for the purpose of serializing data to be loaded by future sessions.
82    #[inline(always)]
83    pub fn from_curr_for_serialization(index: DepNodeIndex) -> Self {
84        SerializedDepNodeIndex::from_u32(index.as_u32())
85    }
86}
87
88const DEP_NODE_SIZE: usize = size_of::<SerializedDepNodeIndex>();
89/// Amount of padding we need to add to the edge list data so that we can retrieve every
90/// SerializedDepNodeIndex with a fixed-size read then mask.
91const DEP_NODE_PAD: usize = DEP_NODE_SIZE - 1;
92/// Number of bits we need to store the number of used bytes in a SerializedDepNodeIndex.
93/// Note that wherever we encode byte widths like this we actually store the number of bytes used
94/// minus 1; for a 4-byte value we technically would have 5 widths to store, but using one byte to
95/// store zeroes (which are relatively rare) is a decent tradeoff to save a bit in our bitfields.
96const DEP_NODE_WIDTH_BITS: usize = DEP_NODE_SIZE / 2;
97
98/// Data for use when recompiling the **current crate**.
99///
100/// There may be unused indices with DepKind::Null in this graph due to batch allocation of
101/// indices to threads.
102#[derive(#[automatically_derived]impl ::core::default::Default for SerializedDepGraph {
    #[inline]
    fn default() -> Self {
        SerializedDepGraph {
            nodes: ::core::default::Default::default(),
            value_fingerprints: ::core::default::Default::default(),
            edge_list_indices: ::core::default::Default::default(),
            edge_list_data: ::core::default::Default::default(),
            reverse_index: ::core::default::Default::default(),
            live_node_count: ::core::default::Default::default(),
            session_count: ::core::default::Default::default(),
            profiler: ::core::default::Default::default(),
        }
    }
}Default)]
103pub struct SerializedDepGraph {
104    /// The set of all DepNodes in the graph
105    nodes: IndexVec<SerializedDepNodeIndex, DepNode>,
106    /// A value fingerprint associated with each [`DepNode`] in [`Self::nodes`],
107    /// typically a hash of the value returned by the node's query in the
108    /// previous incremental-compilation session.
109    ///
110    /// Some nodes don't have a meaningful value hash (e.g. queries with `no_hash`),
111    /// so they store a dummy value here instead (e.g. [`Fingerprint::ZERO`]).
112    value_fingerprints: IndexVec<SerializedDepNodeIndex, Fingerprint>,
113    /// For each DepNode, stores the list of edges originating from that
114    /// DepNode. Encoded as a [start, end) pair indexing into edge_list_data,
115    /// which holds the actual DepNodeIndices of the target nodes.
116    edge_list_indices: IndexVec<SerializedDepNodeIndex, EdgeHeader>,
117    /// A flattened list of all edge targets in the graph, stored in the same
118    /// varint encoding that we use on disk. Edge sources are implicit in edge_list_indices.
119    edge_list_data: Vec<u8>,
120    /// The lazily-built inverse of `nodes`: maps a [`DepNode`] back to its
121    /// [`SerializedDepNodeIndex`] via the node's key fingerprint. See
122    /// [`LazyNodeIndex`].
123    reverse_index: LazyNodeIndex,
124    /// The number of nodes actually encoded, which is below [`Self::index_space_len`]
125    /// whenever a thread left part of its batch of indices unused.
126    live_node_count: usize,
127    /// The number of previous compilation sessions. This is used to generate
128    /// unique anon dep nodes per session.
129    session_count: u64,
130    /// Used to time the lazy per-`DepKind` reverse-index build. `None` only for
131    /// the empty default graph, which is never looked up.
132    profiler: Option<SelfProfilerRef>,
133}
134
135// `SelfProfilerRef` is not `Debug`, so we can't derive this.
136impl std::fmt::Debug for SerializedDepGraph {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        f.debug_struct("SerializedDepGraph")
139            .field("nodes", &self.nodes)
140            .field("value_fingerprints", &self.value_fingerprints)
141            .field("edge_list_indices", &self.edge_list_indices)
142            .field("edge_list_data", &self.edge_list_data)
143            .field("reverse_index", &self.reverse_index)
144            .field("live_node_count", &self.live_node_count)
145            .field("session_count", &self.session_count)
146            .finish_non_exhaustive()
147    }
148}
149
150/// The inverse of [`SerializedDepGraph::nodes`], built lazily per [`DepKind`].
151///
152/// Only few nodes are ever looked up here, and those cluster into a handful of
153/// `DepKind`s. Building a map for every kind up front would be wasted work.
154#[derive(#[automatically_derived]impl ::core::fmt::Debug for LazyNodeIndex {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "LazyNodeIndex nodes_by_kind kinds", &self.nodes_by_kind,
            &&self.kinds)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for LazyNodeIndex {
    #[inline]
    fn default() -> Self {
        LazyNodeIndex {
            nodes_by_kind: ::core::default::Default::default(),
            kinds: ::core::default::Default::default(),
        }
    }
}Default)]
155struct LazyNodeIndex {
156    /// All (non-`Null`) node indices, grouped into contiguous per-`DepKind`
157    /// ranges described by `kinds`. For any non-`Null` `DepKind` `k`, all values in
158    /// `nodes_by_kind[kinds[k].start..][..kinds[k].len]`
159    /// must be `Some` and have kind `k`.
160    nodes_by_kind: Vec<Option<SerializedDepNodeIndex>>,
161    /// For each `DepKind`, the range of `nodes_by_kind` holding its node indices
162    /// and the lazily-built fingerprint map over that range.
163    kinds: Vec<LazyKindIndex>,
164}
165
166#[derive(#[automatically_derived]impl ::core::fmt::Debug for LazyKindIndex {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "LazyKindIndex start len map", &self.start, &self.len, &&self.map)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for LazyKindIndex {
    #[inline]
    fn default() -> Self {
        LazyKindIndex {
            start: ::core::default::Default::default(),
            len: ::core::default::Default::default(),
            map: ::core::default::Default::default(),
        }
    }
}Default)]
167struct LazyKindIndex {
168    /// Offset into `LazyNodeIndex::nodes_by_kind` of this kind's first node.
169    start: u32,
170    /// Number of nodes of this kind.
171    len: u32,
172    /// `key_fingerprint -> node index`, built from this kind's range on first
173    /// lookup. Keys are read from the immutable node array rather than duplicated
174    /// in each table entry. Kinds never looked up never build a map.
175    map: OnceLock<HashTable<SerializedDepNodeIndex>>,
176}
177
178#[inline]
179fn fingerprint_hash(fingerprint: PackedFingerprint) -> u64 {
180    BuildHasherDefault::<Unhasher>::default().hash_one(fingerprint)
181}
182
183impl LazyKindIndex {
184    /// Returns this kind's `key_fingerprint -> node index` map.
185    fn fingerprint_map(
186        &self,
187        kind: DepKind,
188        nodes: &IndexSlice<SerializedDepNodeIndex, DepNode>,
189        nodes_by_kind: &[Option<SerializedDepNodeIndex>],
190        profiler: &Option<SelfProfilerRef>,
191    ) -> &HashTable<SerializedDepNodeIndex> {
192        self.map.get_or_init(|| {
193            let _prof_timer = profiler
194                .as_ref()
195                .map(|p| p.generic_activity("incr_comp_load_dep_graph_reverse_index"));
196            let range = (self.start as usize)..(self.start as usize + self.len as usize);
197            let mut map = HashTable::<SerializedDepNodeIndex>::with_capacity(self.len as usize);
198            for &idx in &nodes_by_kind[range] {
199                let idx = idx.expect("counting sort fills every slot of a kind's range");
200                let node = nodes[idx];
201                if true {
    {
        match (&node.kind, &kind) {
            (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!(node.kind, kind);
202                let entry = map.entry(
203                    fingerprint_hash(node.key_fingerprint),
204                    |&index| nodes[index].key_fingerprint == node.key_fingerprint,
205                    |&index| fingerprint_hash(nodes[index].key_fingerprint),
206                );
207                if #[allow(non_exhaustive_omitted_patterns)] match &entry {
    Entry::Occupied(_) => true,
    _ => false,
}matches!(&entry, Entry::Occupied(_))
208                    // Side effect nodes can legitimately share a fingerprint.
209                    && node.kind != DepKind::SideEffect
210                {
211                    {
    ::core::panicking::panic_fmt(format_args!("Error: A dep graph node ({0:?}) does not have an unique index. Running a clean build on a nightly compiler with `-Z incremental-verify-ich` can help narrow down the issue for reporting. A clean build may also work around the issue.\n\n                         DepNode: {1:?}",
            kind, node));
}panic!(
212                        "Error: A dep graph node ({kind:?}) does not have an unique index. \
213                         Running a clean build on a nightly compiler with \
214                         `-Z incremental-verify-ich` can help narrow down the issue for reporting. \
215                         A clean build may also work around the issue.\n
216                         DepNode: {node:?}"
217                    )
218                }
219                entry.insert(idx);
220            }
221            map
222        })
223    }
224}
225
226impl SerializedDepGraph {
227    #[inline]
228    pub fn edge_targets_from(
229        &self,
230        source: SerializedDepNodeIndex,
231    ) -> impl Iterator<Item = SerializedDepNodeIndex> + Clone {
232        let header = self.edge_list_indices[source];
233        let mut raw = &self.edge_list_data[header.start()..];
234
235        let bytes_per_index = header.bytes_per_index();
236
237        // LLVM doesn't hoist EdgeHeader::mask so we do it ourselves.
238        let mask = header.mask();
239        (0..header.num_edges).map(move |_| {
240            // Doing this slicing in this order ensures that the first bounds check suffices for
241            // all the others.
242            let index = &raw[..DEP_NODE_SIZE];
243            raw = &raw[bytes_per_index..];
244            let index = u32::from_le_bytes(index.try_into().unwrap()) & mask;
245            SerializedDepNodeIndex::from_u32(index)
246        })
247    }
248
249    #[inline]
250    pub fn index_to_node(&self, dep_node_index: SerializedDepNodeIndex) -> &DepNode {
251        &self.nodes[dep_node_index]
252    }
253
254    #[inline]
255    pub fn node_to_index_opt(&self, dep_node: &DepNode) -> Option<SerializedDepNodeIndex> {
256        let kind = self.reverse_index.kinds.get(dep_node.kind.as_usize())?;
257        let map = kind.fingerprint_map(
258            dep_node.kind,
259            &self.nodes,
260            &self.reverse_index.nodes_by_kind,
261            &self.profiler,
262        );
263        map.find(fingerprint_hash(dep_node.key_fingerprint), |&index| {
264            self.nodes[index].key_fingerprint == dep_node.key_fingerprint
265        })
266        .copied()
267    }
268
269    #[inline]
270    pub fn value_fingerprint_for_index(
271        &self,
272        dep_node_index: SerializedDepNodeIndex,
273    ) -> Fingerprint {
274        self.value_fingerprints[dep_node_index]
275    }
276
277    /// The number of dep-node indices, counting those that hold no node.
278    #[inline]
279    pub fn index_space_len(&self) -> usize {
280        self.nodes.len()
281    }
282
283    #[inline]
284    pub fn live_node_count(&self) -> usize {
285        self.live_node_count
286    }
287
288    #[inline]
289    pub fn session_count(&self) -> u64 {
290        self.session_count
291    }
292}
293
294/// A packed representation of an edge's start index and byte width.
295///
296/// This is packed by stealing 2 bits from the start index, which means we only accommodate edge
297/// data arrays up to a quarter of our address space. Which seems fine.
298#[derive(#[automatically_derived]impl ::core::fmt::Debug for EdgeHeader {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "EdgeHeader repr num_edges", &self.repr, &&self.num_edges)
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for EdgeHeader {
}
#[automatically_derived]impl ::core::clone::Clone for EdgeHeader {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for EdgeHeader { }Copy)]
299struct EdgeHeader {
300    repr: usize,
301    num_edges: u32,
302}
303
304impl EdgeHeader {
305    #[inline]
306    fn start(self) -> usize {
307        self.repr >> DEP_NODE_WIDTH_BITS
308    }
309
310    #[inline]
311    fn bytes_per_index(self) -> usize {
312        (self.repr & mask(DEP_NODE_WIDTH_BITS)) + 1
313    }
314
315    #[inline]
316    fn mask(self) -> u32 {
317        mask(self.bytes_per_index() * 8) as u32
318    }
319}
320
321#[inline]
322fn mask(bits: usize) -> usize {
323    usize::MAX >> ((size_of::<usize>() * 8) - bits)
324}
325
326impl SerializedDepGraph {
327    {}
#[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("decode",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(327u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::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_all(&[]) })
                } 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: Arc<SerializedDepGraph> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:330",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(330u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                                d.position()) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let (node_max, node_count, edge_count) =
                d.with_position(d.len() -
                        3 * IntEncodedWithFixedSize::ENCODED_SIZE,
                    |d|
                        {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:336",
                                                    "rustc_middle::dep_graph::serialized",
                                                    ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(336u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                                                d.position()) as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            let node_max =
                                IntEncodedWithFixedSize::decode(d).0 as usize;
                            let node_count =
                                IntEncodedWithFixedSize::decode(d).0 as usize;
                            let edge_count =
                                IntEncodedWithFixedSize::decode(d).0 as usize;
                            (node_max, node_count, edge_count)
                        });
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:342",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(342u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                                d.position()) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:344",
                                    "rustc_middle::dep_graph::serialized",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                                    ::tracing_core::__macro_support::Option::Some(344u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("node_count")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("node_count");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("edge_count")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("edge_count");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_count)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&edge_count)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let graph_bytes =
                d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) -
                    d.position();
            let mut nodes =
                IndexVec::from_elem_n(DepNode {
                        kind: DepKind::Null,
                        key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
                    }, node_max);
            let mut value_fingerprints =
                IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
            let mut edge_list_indices =
                IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 },
                    node_max);
            let mut edge_list_data =
                Vec::with_capacity(graph_bytes -
                        node_count * size_of::<SerializedNodeHeader>());
            for _ in 0..node_count {
                let node_header =
                    SerializedNodeHeader { bytes: d.read_array() };
                let index = node_header.index();
                let node = &mut nodes[index];
                if !(node_header.node().kind != DepKind::Null &&
                            node.kind == DepKind::Null) {
                    ::core::panicking::panic("assertion failed: node_header.node().kind != DepKind::Null && node.kind == DepKind::Null")
                };
                *node = node_header.node();
                value_fingerprints[index] = node_header.value_fingerprint();
                let num_edges =
                    node_header.len().unwrap_or_else(|| d.read_u32());
                let edges_len_bytes =
                    node_header.bytes_per_index() * (num_edges as usize);
                let edges_header =
                    node_header.edges_header(&edge_list_data, num_edges);
                edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
                edge_list_indices[index] = edges_header;
            }
            edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
            let mut kinds = Vec::with_capacity(DepKind::NUM_VARIANTS);
            let mut offset = 0u32;
            for _ in 0..(DepKind::NUM_VARIANTS) {
                let len = d.read_u32();
                kinds.push(LazyKindIndex {
                        start: offset,
                        len,
                        map: OnceLock::new(),
                    });
                offset += len;
            }
            if true {
                {
                    match (&(offset as usize), &node_count) {
                        (left_val, right_val) => {
                            if !(*left_val == *right_val) {
                                let kind = ::core::panicking::AssertKind::Eq;
                                ::core::panicking::assert_failed(kind, &*left_val,
                                    &*right_val, ::core::option::Option::None);
                            }
                        }
                    }
                };
            };
            let session_count = d.read_u64();
            let mut nodes_by_kind =
                ::alloc::vec::from_elem_global(None, node_count);
            let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
            for (idx, node) in nodes.iter_enumerated() {
                if node.kind == DepKind::Null { continue; }
                let k = node.kind.as_usize();
                nodes_by_kind[fill[k] as usize] = Some(idx);
                fill[k] += 1;
            }
            if true {
                if !kinds.iter().zip(&fill).all(|(k, &f)|
                                f == k.start + k.len) {
                    ::core::panicking::panic("assertion failed: kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len)")
                };
            };
            let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
            Arc::new(SerializedDepGraph {
                    nodes,
                    value_fingerprints,
                    edge_list_indices,
                    edge_list_data,
                    reverse_index,
                    live_node_count: node_count,
                    session_count,
                    profiler: Some(profiler.clone()),
                })
        }
    }
}#[instrument(level = "debug", skip(d, profiler))]
328    pub fn decode(d: &mut MemDecoder<'_>, profiler: &SelfProfilerRef) -> Arc<SerializedDepGraph> {
329        // The last 16 bytes are the node count and edge count.
330        debug!("position: {:?}", d.position());
331
332        // `node_max` is the number of indices including empty nodes while `node_count`
333        // is the number of actually encoded nodes.
334        let (node_max, node_count, edge_count) =
335            d.with_position(d.len() - 3 * IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
336                debug!("position: {:?}", d.position());
337                let node_max = IntEncodedWithFixedSize::decode(d).0 as usize;
338                let node_count = IntEncodedWithFixedSize::decode(d).0 as usize;
339                let edge_count = IntEncodedWithFixedSize::decode(d).0 as usize;
340                (node_max, node_count, edge_count)
341            });
342        debug!("position: {:?}", d.position());
343
344        debug!(?node_count, ?edge_count);
345
346        let graph_bytes = d.len() - (3 * IntEncodedWithFixedSize::ENCODED_SIZE) - d.position();
347
348        let mut nodes = IndexVec::from_elem_n(
349            DepNode {
350                kind: DepKind::Null,
351                key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
352            },
353            node_max,
354        );
355        let mut value_fingerprints = IndexVec::from_elem_n(Fingerprint::ZERO, node_max);
356        let mut edge_list_indices =
357            IndexVec::from_elem_n(EdgeHeader { repr: 0, num_edges: 0 }, node_max);
358
359        // This estimation assumes that all of the encoded bytes are for the edge lists or for the
360        // fixed-size node headers. But that's not necessarily true; if any edge list has a length
361        // that spills out of the size we can bit-pack into SerializedNodeHeader then some of the
362        // total serialized size is also used by leb128-encoded edge list lengths. Neglecting that
363        // contribution to graph_bytes means our estimation of the bytes needed for edge_list_data
364        // slightly overshoots. But it cannot overshoot by much; consider that the worse case is
365        // for a node with length 64, which means the spilled 1-byte leb128 length is 1 byte of at
366        // least (34 byte header + 1 byte len + 64 bytes edge data), which is ~1%. A 2-byte leb128
367        // length is about the same fractional overhead and it amortizes for yet greater lengths.
368        let mut edge_list_data =
369            Vec::with_capacity(graph_bytes - node_count * size_of::<SerializedNodeHeader>());
370
371        for _ in 0..node_count {
372            // Decode the header for this edge; the header packs together as many of the fixed-size
373            // fields as possible to limit the number of times we update decoder state.
374            let node_header = SerializedNodeHeader { bytes: d.read_array() };
375
376            let index = node_header.index();
377
378            let node = &mut nodes[index];
379            // Make sure there's no duplicate indices in the dep graph.
380            assert!(node_header.node().kind != DepKind::Null && node.kind == DepKind::Null);
381            *node = node_header.node();
382
383            value_fingerprints[index] = node_header.value_fingerprint();
384
385            // If the length of this node's edge list is small, the length is stored in the header.
386            // If it is not, we fall back to another decoder call.
387            let num_edges = node_header.len().unwrap_or_else(|| d.read_u32());
388
389            // The edges index list uses the same varint strategy as rmeta tables; we select the
390            // number of byte elements per-array not per-element. This lets us read the whole edge
391            // list for a node with one decoder call and also use the on-disk format in memory.
392            let edges_len_bytes = node_header.bytes_per_index() * (num_edges as usize);
393            // The in-memory structure for the edges list stores the byte width of the edges on
394            // this node with the offset into the global edge data array.
395            let edges_header = node_header.edges_header(&edge_list_data, num_edges);
396
397            edge_list_data.extend(d.read_raw_bytes(edges_len_bytes));
398
399            edge_list_indices[index] = edges_header;
400        }
401
402        // When we access the edge list data, we do a fixed-size read from the edge list data then
403        // mask off the bytes that aren't for that edge index, so the last read may dangle off the
404        // end of the array. This padding ensure it doesn't.
405        edge_list_data.extend(&[0u8; DEP_NODE_PAD]);
406
407        // Read the number of nodes of each dep kind, and perform
408        // counting sort for `LazyNodeIndex`.
409        let mut kinds = Vec::with_capacity(DepKind::NUM_VARIANTS);
410        let mut offset = 0u32;
411        for _ in 0..(DepKind::NUM_VARIANTS) {
412            let len = d.read_u32();
413            kinds.push(LazyKindIndex { start: offset, len, map: OnceLock::new() });
414            offset += len;
415        }
416        debug_assert_eq!(offset as usize, node_count);
417
418        let session_count = d.read_u64();
419
420        // Counting sort: place each node index into its kind's range. `fill[k]`
421        // points at the next free slot in kind `k`'s range, so a kind's nodes end
422        // up contiguous. Slots start as `None` and are each filled exactly once
423        // (the counts sum to the number of non-`Null` nodes).
424        let mut nodes_by_kind = vec![None; node_count];
425        let mut fill: Vec<u32> = kinds.iter().map(|k| k.start).collect();
426        for (idx, node) in nodes.iter_enumerated() {
427            // Unused indices from batch allocation stay `Null`; they carry no
428            // encoded node and are never looked up by fingerprint, so skip them.
429            if node.kind == DepKind::Null {
430                continue;
431            }
432            let k = node.kind.as_usize();
433            nodes_by_kind[fill[k] as usize] = Some(idx);
434            fill[k] += 1;
435        }
436        // Each kind's range was filled exactly to its end.
437        debug_assert!(kinds.iter().zip(&fill).all(|(k, &f)| f == k.start + k.len));
438        let reverse_index = LazyNodeIndex { nodes_by_kind, kinds };
439
440        Arc::new(SerializedDepGraph {
441            nodes,
442            value_fingerprints,
443            edge_list_indices,
444            edge_list_data,
445            reverse_index,
446            live_node_count: node_count,
447            session_count,
448            profiler: Some(profiler.clone()),
449        })
450    }
451}
452
453/// A packed representation of all the fixed-size fields in a `NodeInfo`.
454///
455/// This stores in one byte array:
456/// * The value `Fingerprint` in the `NodeInfo`
457/// * The key `Fingerprint` in `DepNode` that is in this `NodeInfo`
458/// * The `DepKind`'s discriminant (a u16, but not all bits are used...)
459/// * The byte width of the encoded edges for this node
460/// * In whatever bits remain, the length of the edge list for this node, if it fits
461struct SerializedNodeHeader {
462    // 2 bytes for the DepNode
463    // 4 bytes for the index
464    // 16 for Fingerprint in DepNode
465    // 16 for Fingerprint in NodeInfo
466    bytes: [u8; 38],
467}
468
469// The fields of a `SerializedNodeHeader`, this struct is an implementation detail and exists only
470// to make the implementation of `SerializedNodeHeader` simpler.
471struct Unpacked {
472    len: Option<u32>,
473    bytes_per_index: usize,
474    kind: DepKind,
475    index: SerializedDepNodeIndex,
476    key_fingerprint: PackedFingerprint,
477    value_fingerprint: Fingerprint,
478}
479
480// Bit fields, where
481// M: bits used to store the length of a node's edge list
482// N: bits used to store the byte width of elements of the edge list
483// are
484// 0..M    length of the edge
485// M..M+N  bytes per index
486// M+N..16 kind
487impl SerializedNodeHeader {
488    const TOTAL_BITS: usize = size_of::<DepKind>() * 8;
489    const LEN_BITS: usize = Self::TOTAL_BITS - Self::KIND_BITS - Self::WIDTH_BITS;
490    const WIDTH_BITS: usize = DEP_NODE_WIDTH_BITS;
491    const KIND_BITS: usize = Self::TOTAL_BITS - DepKind::MAX.leading_zeros() as usize;
492    const MAX_INLINE_LEN: usize = (u16::MAX as usize >> (Self::TOTAL_BITS - Self::LEN_BITS)) - 1;
493
494    #[inline]
495    fn new(
496        node: &DepNode,
497        index: DepNodeIndex,
498        value_fingerprint: Fingerprint,
499        edge_max_index: u32,
500        edge_count: usize,
501    ) -> Self {
502        if true {
    {
        match (&Self::TOTAL_BITS,
                &(Self::LEN_BITS + Self::WIDTH_BITS + Self::KIND_BITS)) {
            (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::TOTAL_BITS, Self::LEN_BITS + Self::WIDTH_BITS + Self::KIND_BITS);
503
504        let mut head = node.kind.as_u16();
505
506        let free_bytes = edge_max_index.leading_zeros() as usize / 8;
507        let bytes_per_index = (DEP_NODE_SIZE - free_bytes).saturating_sub(1);
508        head |= (bytes_per_index as u16) << Self::KIND_BITS;
509
510        // Encode number of edges + 1 so that we can reserve 0 to indicate that the len doesn't fit
511        // in this bitfield.
512        if edge_count <= Self::MAX_INLINE_LEN {
513            head |= (edge_count as u16 + 1) << (Self::KIND_BITS + Self::WIDTH_BITS);
514        }
515
516        let hash: Fingerprint = node.key_fingerprint.into();
517
518        // Using half-open ranges ensures an unconditional panic if we get the magic numbers wrong.
519        let mut bytes = [0u8; 38];
520        bytes[..2].copy_from_slice(&head.to_le_bytes());
521        bytes[2..6].copy_from_slice(&index.as_u32().to_le_bytes());
522        bytes[6..22].copy_from_slice(&hash.to_le_bytes());
523        bytes[22..].copy_from_slice(&value_fingerprint.to_le_bytes());
524
525        #[cfg(debug_assertions)]
526        {
527            let res = Self { bytes };
528            {
    match (&value_fingerprint, &res.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::None);
            }
        }
    }
};assert_eq!(value_fingerprint, res.value_fingerprint());
529            {
    match (&*node, &res.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!(*node, res.node());
530            if let Some(len) = res.len() {
531                {
    match (&edge_count, &(len as usize)) {
        (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!(edge_count, len as usize);
532            }
533        }
534        Self { bytes }
535    }
536
537    #[inline]
538    fn unpack(&self) -> Unpacked {
539        let head = u16::from_le_bytes(self.bytes[..2].try_into().unwrap());
540        let index = u32::from_le_bytes(self.bytes[2..6].try_into().unwrap());
541        let key_fingerprint = self.bytes[6..22].try_into().unwrap();
542        let value_fingerprint = self.bytes[22..].try_into().unwrap();
543
544        let kind = head & mask(Self::KIND_BITS) as u16;
545        let bytes_per_index = (head >> Self::KIND_BITS) & mask(Self::WIDTH_BITS) as u16;
546        let len = (head as u32) >> (Self::WIDTH_BITS + Self::KIND_BITS);
547
548        Unpacked {
549            len: len.checked_sub(1),
550            bytes_per_index: bytes_per_index as usize + 1,
551            kind: DepKind::from_u16(kind),
552            index: SerializedDepNodeIndex::from_u32(index),
553            key_fingerprint: Fingerprint::from_le_bytes(key_fingerprint).into(),
554            value_fingerprint: Fingerprint::from_le_bytes(value_fingerprint),
555        }
556    }
557
558    #[inline]
559    fn len(&self) -> Option<u32> {
560        self.unpack().len
561    }
562
563    #[inline]
564    fn bytes_per_index(&self) -> usize {
565        self.unpack().bytes_per_index
566    }
567
568    #[inline]
569    fn index(&self) -> SerializedDepNodeIndex {
570        self.unpack().index
571    }
572
573    #[inline]
574    fn value_fingerprint(&self) -> Fingerprint {
575        self.unpack().value_fingerprint
576    }
577
578    #[inline]
579    fn node(&self) -> DepNode {
580        let Unpacked { kind, key_fingerprint, .. } = self.unpack();
581        DepNode { kind, key_fingerprint }
582    }
583
584    #[inline]
585    fn edges_header(&self, edge_list_data: &[u8], num_edges: u32) -> EdgeHeader {
586        EdgeHeader {
587            repr: (edge_list_data.len() << DEP_NODE_WIDTH_BITS) | (self.bytes_per_index() - 1),
588            num_edges,
589        }
590    }
591}
592
593#[derive(#[automatically_derived]impl<'a> ::core::fmt::Debug for NodeInfo<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "NodeInfo node value_fingerprint edges", &self.node,
            &self.value_fingerprint, &&self.edges)
    }
}Debug)]
594struct NodeInfo<'a> {
595    node: DepNode,
596    value_fingerprint: Fingerprint,
597    edges: &'a [DepNodeIndex],
598}
599
600impl NodeInfo<'_> {
601    fn encode(&self, e: &mut MemEncoder, index: DepNodeIndex) {
602        let NodeInfo { ref node, value_fingerprint, edges } = *self;
603        // The largest index picks the byte width of the edge list.
604        let edge_max = edges.iter().map(|e| e.as_u32()).max().unwrap_or(0);
605        let header =
606            SerializedNodeHeader::new(node, index, value_fingerprint, edge_max, edges.len());
607        e.write_array(header.bytes);
608
609        if header.len().is_none() {
610            // The edges are all unique and the number of unique indices is less than u32::MAX.
611            e.emit_u32(edges.len().try_into().unwrap());
612        }
613
614        let bytes_per_index = header.bytes_per_index();
615        for node_index in edges.iter() {
616            e.write_with(|dest| {
617                *dest = node_index.as_u32().to_le_bytes();
618                bytes_per_index
619            });
620        }
621    }
622}
623
624struct Stat {
625    kind: DepKind,
626    node_counter: u64,
627    edge_counter: u64,
628}
629
630struct LocalEncoderState {
631    next_node_index: u32,
632    remaining_node_index: u32,
633    encoder: MemEncoder,
634    node_count: usize,
635    edge_count: usize,
636
637    /// Stores the number of times we've encoded each dep kind.
638    kind_stats: Vec<u32>,
639}
640
641struct LocalEncoderResult {
642    node_max: u32,
643    node_count: usize,
644    edge_count: usize,
645
646    /// Stores the number of times we've encoded each dep kind.
647    kind_stats: Vec<u32>,
648}
649
650struct EncoderState {
651    next_node_index: AtomicU64,
652    previous: Arc<SerializedDepGraph>,
653    file: Lock<Option<FileEncoder>>,
654    local: WorkerLocal<RefCell<LocalEncoderState>>,
655    stats: Option<Lock<FxHashMap<DepKind, Stat>>>,
656}
657
658impl EncoderState {
659    fn new(encoder: FileEncoder, record_stats: bool, previous: Arc<SerializedDepGraph>) -> Self {
660        Self {
661            previous,
662            next_node_index: AtomicU64::new(0),
663            stats: record_stats.then(|| Lock::new(FxHashMap::default())),
664            file: Lock::new(Some(encoder)),
665            local: WorkerLocal::new(|_| {
666                RefCell::new(LocalEncoderState {
667                    next_node_index: 0,
668                    remaining_node_index: 0,
669                    edge_count: 0,
670                    node_count: 0,
671                    encoder: MemEncoder::new(),
672                    kind_stats: iter::repeat_n(0, DepKind::NUM_VARIANTS).collect(),
673                })
674            }),
675        }
676    }
677
678    #[inline]
679    fn next_index(&self, local: &mut LocalEncoderState) -> DepNodeIndex {
680        if local.remaining_node_index == 0 {
681            const COUNT: u32 = 256;
682
683            // We assume that there won't be enough active threads to overflow `u64` from `u32::MAX` here.
684            // This can exceed u32::MAX by at most `N` * `COUNT` where `N` is the thread pool count since
685            // `try_into().unwrap()` will make threads panic when `self.next_node_index` exceeds u32::MAX.
686            local.next_node_index =
687                self.next_node_index.fetch_add(COUNT as u64, Ordering::Relaxed).try_into().unwrap();
688
689            // Check that we'll stay within `u32`
690            local.next_node_index.checked_add(COUNT).unwrap();
691
692            local.remaining_node_index = COUNT;
693        }
694
695        DepNodeIndex::from_u32(local.next_node_index)
696    }
697
698    /// Marks the index previously returned by `next_index` as used.
699    #[inline]
700    fn bump_index(&self, local: &mut LocalEncoderState) {
701        local.remaining_node_index -= 1;
702        local.next_node_index += 1;
703        local.node_count += 1;
704    }
705
706    #[inline]
707    fn record(
708        &self,
709        node: &DepNode,
710        index: DepNodeIndex,
711        edge_count: usize,
712        edges: &[DepNodeIndex],
713        retained_graph: &Option<Lock<RetainedDepGraph>>,
714        local: &mut LocalEncoderState,
715    ) {
716        local.kind_stats[node.kind.as_usize()] += 1;
717        local.edge_count += edge_count;
718
719        if let Some(retained_graph) = &retained_graph {
720            // Outline the build of the full dep graph as it's typically disabled and cold.
721            outline(move || {
722                // Block on the lock rather than using `try_lock`: under the parallel frontend
723                // several threads record nodes concurrently, and dropping a node on lock
724                // contention would make the retained graph nondeterministic. Readers take a
725                // clone of the graph (`retained_dep_graph`) rather than holding the lock, so
726                // this never deadlocks against a reentrant `record`.
727                retained_graph.lock().push(index, *node, edges);
728            });
729        }
730
731        if let Some(stats) = &self.stats {
732            let kind = node.kind;
733
734            // Outline the stats code as it's typically disabled and cold.
735            outline(move || {
736                let mut stats = stats.lock();
737                let stat =
738                    stats.entry(kind).or_insert(Stat { kind, node_counter: 0, edge_counter: 0 });
739                stat.node_counter += 1;
740                stat.edge_counter += edge_count as u64;
741            });
742        }
743    }
744
745    #[inline]
746    fn flush_mem_encoder(&self, local: &mut LocalEncoderState) {
747        let data = &mut local.encoder.data;
748        if data.len() > 64 * 1024 {
749            self.file.lock().as_mut().unwrap().emit_raw_bytes(&data[..]);
750            data.clear();
751        }
752    }
753
754    /// Encodes a node to the current graph.
755    fn encode_node(
756        &self,
757        index: DepNodeIndex,
758        node: &NodeInfo<'_>,
759        retained_graph: &Option<Lock<RetainedDepGraph>>,
760        local: &mut LocalEncoderState,
761    ) {
762        node.encode(&mut local.encoder, index);
763        self.flush_mem_encoder(&mut *local);
764        self.record(&node.node, index, node.edges.len(), node.edges, retained_graph, &mut *local);
765    }
766
767    /// Encodes a node that was promoted from the previous graph, reading the node and its
768    /// fingerprint directly from the previous dep graph. It expects all edges to already
769    /// have a new dep node index assigned.
770    #[inline]
771    fn encode_promoted_node(
772        &self,
773        index: DepNodeIndex,
774        prev_index: SerializedDepNodeIndex,
775        retained_graph: &Option<Lock<RetainedDepGraph>>,
776        local: &mut LocalEncoderState,
777        edges: &[DepNodeIndex],
778    ) {
779        let node = NodeInfo {
780            node: *self.previous.index_to_node(prev_index),
781            value_fingerprint: self.previous.value_fingerprint_for_index(prev_index),
782            edges,
783        };
784        self.encode_node(index, &node, retained_graph, local);
785    }
786
787    fn finish(&self, profiler: &SelfProfilerRef, current: &CurrentDepGraph) -> FileEncodeResult {
788        // Prevent more indices from being allocated.
789        self.next_node_index.store(u32::MAX as u64 + 1, Ordering::SeqCst);
790
791        let results = broadcast(|_| {
792            let mut local = self.local.borrow_mut();
793
794            // Prevent more indices from being allocated on this thread.
795            local.remaining_node_index = 0;
796
797            let data = mem::take(&mut local.encoder.data);
798            self.file.lock().as_mut().unwrap().emit_raw_bytes(&data);
799
800            LocalEncoderResult {
801                kind_stats: local.kind_stats.clone(),
802                node_max: local.next_node_index,
803                node_count: local.node_count,
804                edge_count: local.edge_count,
805            }
806        });
807
808        let mut encoder = self.file.lock().take().unwrap();
809
810        let mut kind_stats: Vec<u32> = iter::repeat_n(0, DepKind::NUM_VARIANTS).collect();
811
812        let mut node_max = 0;
813        let mut node_count = 0;
814        let mut edge_count = 0;
815
816        for result in results {
817            node_max = max(node_max, result.node_max);
818            node_count += result.node_count;
819            edge_count += result.edge_count;
820            for (i, stat) in result.kind_stats.iter().enumerate() {
821                kind_stats[i] += stat;
822            }
823        }
824
825        // Encode the number of each dep kind encountered
826        for count in kind_stats.iter() {
827            count.encode(&mut encoder);
828        }
829
830        self.previous.session_count.checked_add(1).unwrap().encode(&mut encoder);
831
832        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:832",
                        "rustc_middle::dep_graph::serialized",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                        ::tracing_core::__macro_support::Option::Some(832u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("node_max")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("node_max");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("node_count")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("node_count");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("edge_count")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("edge_count");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_max)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&node_count)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&edge_count)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?node_max, ?node_count, ?edge_count);
833        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:833",
                        "rustc_middle::dep_graph::serialized",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                        ::tracing_core::__macro_support::Option::Some(833u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                    encoder.position()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("position: {:?}", encoder.position());
834        IntEncodedWithFixedSize(node_max.try_into().unwrap()).encode(&mut encoder);
835        IntEncodedWithFixedSize(node_count.try_into().unwrap()).encode(&mut encoder);
836        IntEncodedWithFixedSize(edge_count.try_into().unwrap()).encode(&mut encoder);
837        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs:837",
                        "rustc_middle::dep_graph::serialized",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6181cc4f077f1a16ce605e297173b01c6ddff553/compiler/rustc_middle/src/dep_graph/serialized.rs"),
                        ::tracing_core::__macro_support::Option::Some(837u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::serialized"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("position: {0:?}",
                                                    encoder.position()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("position: {:?}", encoder.position());
838        // Drop the encoder so that nothing is written after the counts.
839        let result = encoder.finish();
840        if let Ok(position) = result {
841            // FIXME(rylev): we hardcode the dep graph file name so we
842            // don't need a dependency on rustc_incremental just for that.
843            profiler.artifact_size("dep_graph", "dep-graph.bin", position as u64);
844        }
845
846        self.print_incremental_info(current, node_count, edge_count);
847
848        result
849    }
850
851    fn print_incremental_info(
852        &self,
853        current: &CurrentDepGraph,
854        total_node_count: usize,
855        total_edge_count: usize,
856    ) {
857        if let Some(record_stats) = &self.stats {
858            let record_stats = record_stats.lock();
859            // `stats` is sorted below so we can allow this lint here.
860            #[allow(rustc::potential_query_instability)]
861            let mut stats: Vec<_> = record_stats.values().collect();
862            stats.sort_by_key(|s| -(s.node_counter as i64));
863
864            const SEPARATOR: &str = "[incremental] --------------------------------\
865                                     ----------------------------------------------\
866                                     ------------";
867
868            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
869            { ::std::io::_eprint(format_args!("[incremental] DepGraph Statistics\n")); };eprintln!("[incremental] DepGraph Statistics");
870            { ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
871            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
872            {
    ::std::io::_eprint(format_args!("[incremental] Total Node Count: {0}\n",
            total_node_count));
};eprintln!("[incremental] Total Node Count: {}", total_node_count);
873            {
    ::std::io::_eprint(format_args!("[incremental] Total Edge Count: {0}\n",
            total_edge_count));
};eprintln!("[incremental] Total Edge Count: {}", total_edge_count);
874
875            if truecfg!(debug_assertions) {
876                let total_read_count = current.total_read_count.load(Ordering::Relaxed);
877                let total_duplicate_read_count =
878                    current.total_duplicate_read_count.load(Ordering::Relaxed);
879                {
    ::std::io::_eprint(format_args!("[incremental] Total Edge Reads: {0}\n",
            total_read_count));
};eprintln!("[incremental] Total Edge Reads: {total_read_count}");
880                {
    ::std::io::_eprint(format_args!("[incremental] Total Duplicate Edge Reads: {0}\n",
            total_duplicate_read_count));
};eprintln!("[incremental] Total Duplicate Edge Reads: {total_duplicate_read_count}");
881            }
882
883            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
884            {
    ::std::io::_eprint(format_args!("[incremental]  {0:<36}| {1:<17}| {2:<12}| {3:<17}|\n",
            "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"));
};eprintln!(
885                "[incremental]  {:<36}| {:<17}| {:<12}| {:<17}|",
886                "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count"
887            );
888            { ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
889
890            for stat in stats {
891                let node_kind_ratio =
892                    (100.0 * (stat.node_counter as f64)) / (total_node_count as f64);
893                let node_kind_avg_edges = (stat.edge_counter as f64) / (stat.node_counter as f64);
894
895                {
    ::std::io::_eprint(format_args!("[incremental]  {0:<36}|{1:>16.1}% |{2:>12} |{3:>17.1} |\n",
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0:?}", stat.kind))
                }), node_kind_ratio, stat.node_counter, node_kind_avg_edges));
};eprintln!(
896                    "[incremental]  {:<36}|{:>16.1}% |{:>12} |{:>17.1} |",
897                    format!("{:?}", stat.kind),
898                    node_kind_ratio,
899                    stat.node_counter,
900                    node_kind_avg_edges,
901                );
902            }
903
904            { ::std::io::_eprint(format_args!("{0}\n", SEPARATOR)); };eprintln!("{SEPARATOR}");
905            { ::std::io::_eprint(format_args!("[incremental]\n")); };eprintln!("[incremental]");
906        }
907    }
908}
909
910pub(crate) struct GraphEncoder {
911    profiler: SelfProfilerRef,
912    status: EncoderState,
913    /// In-memory copy of the dep graph; only present if `-Zquery-dep-graph` is set.
914    retained_graph: Option<Lock<RetainedDepGraph>>,
915}
916
917impl GraphEncoder {
918    pub(crate) fn new(
919        sess: &Session,
920        encoder: FileEncoder,
921        prev_index_space_len: usize,
922        previous: Arc<SerializedDepGraph>,
923    ) -> Self {
924        let retained_graph = sess
925            .opts
926            .unstable_opts
927            .query_dep_graph
928            .then(|| Lock::new(RetainedDepGraph::new(prev_index_space_len)));
929        let status = EncoderState::new(encoder, sess.opts.unstable_opts.incremental_info, previous);
930        GraphEncoder { status, retained_graph, profiler: sess.prof.clone() }
931    }
932
933    pub(crate) fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
934        self.retained_graph.as_ref().map(|retained_graph| retained_graph.lock().clone())
935    }
936
937    /// Encodes a node that does not exists in the previous graph.
938    pub(crate) fn send_new(
939        &self,
940        node: DepNode,
941        value_fingerprint: Fingerprint,
942        edges: &[DepNodeIndex],
943    ) -> DepNodeIndex {
944        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
945        let node = NodeInfo { node, value_fingerprint, edges };
946        let mut local = self.status.local.borrow_mut();
947        let index = self.status.next_index(&mut *local);
948        self.status.bump_index(&mut *local);
949        self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
950        index
951    }
952
953    /// Encodes a node that exists in the previous graph, but was re-executed.
954    ///
955    /// This will also ensure the dep node is colored either red or green.
956    pub(crate) fn send_and_color(
957        &self,
958        prev_index: SerializedDepNodeIndex,
959        colors: &DepNodeColorMap,
960        node: DepNode,
961        value_fingerprint: Fingerprint,
962        edges: &[DepNodeIndex],
963        is_green: bool,
964    ) -> DepNodeIndex {
965        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
966        let node = NodeInfo { node, value_fingerprint, edges };
967
968        let mut local = self.status.local.borrow_mut();
969
970        let index = self.status.next_index(&mut *local);
971        let color = if is_green { DesiredColor::Green { index } } else { DesiredColor::Red };
972
973        // Use `try_set_color` to avoid racing when `send_promoted` is called concurrently
974        // on the same index.
975        match colors.try_set_color(prev_index, color) {
976            TrySetColorResult::Success => {}
977            TrySetColorResult::AlreadyRed => {
    ::core::panicking::panic_fmt(format_args!("dep node {0:?} is unexpectedly red",
            prev_index));
}panic!("dep node {prev_index:?} is unexpectedly red"),
978            TrySetColorResult::AlreadyGreen { index } => return index,
979        }
980
981        self.status.bump_index(&mut *local);
982        self.status.encode_node(index, &node, &self.retained_graph, &mut *local);
983        index
984    }
985
986    /// Encodes a node that was promoted from the previous graph. It reads the information directly
987    /// from the previous dep graph and expects all edges to already have a new dep node index
988    /// assigned.
989    ///
990    /// Tries to mark the dep node green, and returns Some if it is now green,
991    /// or None if had already been concurrently marked red.
992    #[inline]
993    pub(crate) fn send_promoted(
994        &self,
995        prev_index: SerializedDepNodeIndex,
996        colors: &DepNodeColorMap,
997        edges: &[DepNodeIndex],
998    ) -> Option<DepNodeIndex> {
999        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph");
1000
1001        let mut local = self.status.local.borrow_mut();
1002        let index = self.status.next_index(&mut *local);
1003
1004        // Use `try_set_color` to avoid racing when `send_promoted` or `send_and_color`
1005        // is called concurrently on the same index.
1006        match colors.try_set_color(prev_index, DesiredColor::Green { index }) {
1007            TrySetColorResult::Success => {
1008                self.status.bump_index(&mut *local);
1009                self.status.encode_promoted_node(
1010                    index,
1011                    prev_index,
1012                    &self.retained_graph,
1013                    &mut *local,
1014                    edges,
1015                );
1016                Some(index)
1017            }
1018            TrySetColorResult::AlreadyRed => None,
1019            TrySetColorResult::AlreadyGreen { index } => Some(index),
1020        }
1021    }
1022
1023    pub(crate) fn finish(&self, current: &CurrentDepGraph) -> FileEncodeResult {
1024        let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish");
1025
1026        self.status.finish(&self.profiler, current)
1027    }
1028}