1use std::assert_matches;
2use std::cell::Cell;
3use std::fmt::Debug;
4use std::hash::Hash;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicU32, Ordering};
78use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
9use rustc_data_structures::fx::FxHashSet;
10use rustc_data_structures::profiling::QueryInvocationId;
11use rustc_data_structures::sharded::ShardedHashMap;
12use rustc_data_structures::stable_hash::{StableHash, StableHasher};
13use rustc_data_structures::sync::{AtomicU64, Lock, WorkerLocal};
14use rustc_data_structures::unord::UnordMap;
15use rustc_errors::DiagInner;
16use rustc_index::IndexVec;
17use rustc_macros::{Decodable, Encodable};
18use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
19use rustc_session::Session;
20use rustc_span::Symbol;
21use smallvec::SmallVec;
22use tracing::instrument;
23#[cfg(debug_assertions)]
24use {super::debug::EdgeFilter, std::env};
2526use super::edges::{ReadsRecorder, SMALL_READS_MAX, TaskReads};
27use super::retained::RetainedDepGraph;
28use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex};
29use super::{DepKind, DepNode, WorkProductId, read_deps, with_deps};
30use crate::ich::StableHashState;
31use crate::ty::TyCtxt;
32use crate::verify_ich::incremental_verify_ich;
3334/// Tracks 'side effects' for a particular query.
35/// This struct is saved to disk along with the query result,
36/// and loaded from disk if we mark the query as green.
37/// This allows us to 'replay' changes to global state
38/// that would otherwise only occur if we actually
39/// executed the query method.
40///
41/// Each side effect gets an unique dep node index which is added
42/// as a dependency of the query which had the effect.
43#[derive(#[automatically_derived]
impl ::core::fmt::Debug for QuerySideEffect {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
QuerySideEffect::Diagnostic(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Diagnostic", &__self_0),
QuerySideEffect::CheckFeature { symbol: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"CheckFeature", "symbol", &__self_0),
}
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for QuerySideEffect {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
QuerySideEffect::Diagnostic(ref __binding_0) => { 0usize }
QuerySideEffect::CheckFeature { symbol: ref __binding_0 } =>
{
1usize
}
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
QuerySideEffect::Diagnostic(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
QuerySideEffect::CheckFeature { symbol: ref __binding_0 } =>
{
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for QuerySideEffect {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
QuerySideEffect::Diagnostic(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
QuerySideEffect::CheckFeature {
symbol: ::rustc_serialize::Decodable::decode(__decoder),
}
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `QuerySideEffect`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
44pub enum QuerySideEffect {
45/// Stores a diagnostic emitted during query execution.
46 /// This diagnostic will be re-emitted if we mark
47 /// the query as green, as that query will have the side
48 /// effect dep node as a dependency.
49Diagnostic(DiagInner),
50/// Records the feature used during query execution.
51 /// This feature will be inserted into `query_system.used_features`
52 /// if we mark the query as green, as that query will have
53 /// the side effect dep node as a dependency.
54CheckFeature { symbol: Symbol },
55}
5657#[derive(#[automatically_derived]
impl ::core::clone::Clone for DepGraph {
#[inline]
fn clone(&self) -> DepGraph {
DepGraph {
data: ::core::clone::Clone::clone(&self.data),
virtual_dep_node_index: ::core::clone::Clone::clone(&self.virtual_dep_node_index),
}
}
}Clone)]
58pub struct DepGraph {
59 data: Option<Arc<DepGraphData>>,
6061/// This field is used for assigning DepNodeIndices when running in
62 /// non-incremental mode. Even in non-incremental mode we make sure that
63 /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
64 /// ID is used for self-profiling.
65virtual_dep_node_index: Arc<AtomicU32>,
66}
6768#[automatically_derived]
impl ::core::marker::Copy for DepNodeIndex { }
impl DepNodeIndex {
#[doc = r" Maximum value the index can take, as a `u32`."]
pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[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 <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 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 <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
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 <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
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 DepNodeIndex {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for DepNodeIndex {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for DepNodeIndex {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl From<DepNodeIndex> for u32 {
#[inline]
fn from(v: DepNodeIndex) -> u32 { v.as_u32() }
}
impl From<DepNodeIndex> for usize {
#[inline]
fn from(v: DepNodeIndex) -> usize { v.as_usize() }
}
impl From<usize> for DepNodeIndex {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for DepNodeIndex {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for DepNodeIndex {}
impl ::std::cmp::PartialEq for DepNodeIndex {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for DepNodeIndex {}
impl ::std::hash::Hash for DepNodeIndex {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl ::std::fmt::Debug for DepNodeIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
69pub struct DepNodeIndex {}
70}7172// We store a large collection of these in `prev_index_to_index` during
73// non-full incremental builds, and want to ensure that the element size
74// doesn't inadvertently increase.
75const _: [(); 4] = [(); ::std::mem::size_of::<Option<DepNodeIndex>>()];rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
7677impl DepNodeIndex {
78const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
79pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
80}
8182impl From<DepNodeIndex> for QueryInvocationId {
83#[inline(always)]
84fn from(dep_node_index: DepNodeIndex) -> Self {
85QueryInvocationId(dep_node_index.as_u32())
86 }
87}
8889pub(crate) struct MarkFrame<'a> {
90 index: SerializedDepNodeIndex,
91 parent: Option<&'a MarkFrame<'a>>,
92}
9394/// The edge list of one node being marked green: it occupies `buf[start..]` of the shared
95/// scratch buffer and is popped again on drop, restoring the buffer for the enclosing call.
96struct EdgeFrame<'a> {
97 buf: &'a mut Vec<DepNodeIndex>,
98 start: usize,
99}
100101impl<'a> EdgeFrame<'a> {
102#[inline]
103fn new(buf: &'a mut Vec<DepNodeIndex>) -> Self {
104EdgeFrame { start: buf.len(), buf }
105 }
106107#[inline]
108fn push(&mut self, edge: DepNodeIndex) {
109self.buf.push(edge);
110 }
111112/// The edges pushed onto this frame so far.
113#[inline]
114fn get(&self) -> &[DepNodeIndex] {
115&self.buf[self.start..]
116 }
117}
118119impl Dropfor EdgeFrame<'_> {
120#[inline]
121fn drop(&mut self) {
122self.buf.truncate(self.start);
123 }
124}
125126#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DepNodeColor {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DepNodeColor::Green(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Green",
&__self_0),
DepNodeColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
DepNodeColor::Unknown =>
::core::fmt::Formatter::write_str(f, "Unknown"),
}
}
}Debug)]
127pub(super) enum DepNodeColor {
128 Green(DepNodeIndex),
129 Red,
130 Unknown,
131}
132133pub struct DepGraphData {
134/// The new encoding of the dependency graph, optimized for red/green
135 /// tracking. The `current` field is the dependency graph of only the
136 /// current compilation session: We don't merge the previous dep-graph into
137 /// current one anymore, but we do reference shared data to save space.
138current: CurrentDepGraph,
139140/// The dep-graph from the previous compilation session. It contains all
141 /// nodes and edges as well as all fingerprints of nodes that have them.
142previous: Arc<SerializedDepGraph>,
143144 colors: DepNodeColorMap,
145146/// When we load, there may be `.o` files, cached MIR, or other such
147 /// things available to us. If we find that they are not dirty, we
148 /// load the path to the file storing those work-products here into
149 /// this map. We can later look for and extract that data.
150previous_work_products: WorkProductMap,
151152/// Used by incremental compilation tests to assert that
153 /// a particular query result was decoded from disk
154 /// (not just marked green)
155debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
156157/// Per-worker edge buffer amortized across `try_mark_green` calls.
158green_edge_buf: WorkerLocal<Cell<Vec<DepNodeIndex>>>,
159160/// Pool of read recorders, amortized across tasks. Global rather than per worker so the
161 /// retained memory is bounded by the total number of concurrently recording tasks.
162read_recorder_pool: Lock<Vec<ReadsRecorder>>,
163}
164165pub fn hash_result<R>(hcx: &mut StableHashState<'_>, result: &R) -> Fingerprint166where
167R: StableHash,
168{
169let mut stable_hasher = StableHasher::new();
170result.stable_hash(hcx, &mut stable_hasher);
171stable_hasher.finish()
172}
173174impl DepGraph {
175pub fn new(
176 session: &Session,
177 prev_graph: Arc<SerializedDepGraph>,
178 prev_work_products: WorkProductMap,
179 encoder: FileEncoder<'static>,
180 ) -> DepGraph {
181let prev_index_space_len = prev_graph.index_space_len();
182183let current =
184CurrentDepGraph::new(session, prev_index_space_len, encoder, Arc::clone(&prev_graph));
185186let colors = DepNodeColorMap::new(prev_index_space_len);
187188// Instantiate a node with zero dependencies only once for anonymous queries.
189let _green_node_index = current.alloc_new_node(
190DepNode { kind: DepKind::AnonZeroDeps, key_fingerprint: current.anon_id_seed.into() },
191&[],
192Fingerprint::ZERO,
193 );
194{
match (&_green_node_index, &DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(_green_node_index, DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE);
195196// Create a single always-red node, with no dependencies of its own.
197 // Other nodes can use the always-red node as a fake dependency, to
198 // ensure that their dependency list will never be all-green.
199let red_node_index = current.alloc_new_node(
200DepNode { kind: DepKind::Red, key_fingerprint: Fingerprint::ZERO.into() },
201&[],
202Fingerprint::ZERO,
203 );
204{
match (&red_node_index, &DepNodeIndex::FOREVER_RED_NODE) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(red_node_index, DepNodeIndex::FOREVER_RED_NODE);
205if prev_index_space_len > 0 {
206let prev_index =
207const { SerializedDepNodeIndex::from_u32(DepNodeIndex::FOREVER_RED_NODE.as_u32()) };
208let result = colors.try_set_color(prev_index, DesiredColor::Red);
209{
match result {
TrySetColorResult::Success => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TrySetColorResult::Success", ::core::option::Option::None);
}
}
};assert_matches!(result, TrySetColorResult::Success);
210 }
211212DepGraph {
213 data: Some(Arc::new(DepGraphData {
214 previous_work_products: prev_work_products,
215current,
216 previous: prev_graph,
217colors,
218 debug_loaded_from_disk: Default::default(),
219 green_edge_buf: WorkerLocal::default(),
220 read_recorder_pool: Lock::new(Vec::new()),
221 })),
222 virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
223 }
224 }
225226pub fn new_disabled() -> DepGraph {
227DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
228 }
229230#[inline]
231pub fn data(&self) -> Option<&DepGraphData> {
232self.data.as_deref()
233 }
234235/// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
236#[inline]
237pub fn is_fully_enabled(&self) -> bool {
238self.data.is_some()
239 }
240241/// Returns a clone of the in-memory retained dep graph, if it is being built
242 /// (i.e. `-Zquery-dep-graph` is set). Cloning rather than exposing the lock keeps
243 /// callers from holding it while forcing queries, which would deadlock against a
244 /// reentrant `record` under the parallel frontend.
245pub fn retained_dep_graph(&self) -> Option<RetainedDepGraph> {
246self.data.as_ref().and_then(|data| data.current.encoder.retained_dep_graph())
247 }
248249pub fn assert_ignored(&self) {
250if let Some(..) = self.data {
251read_deps(|task_deps| {
252{
match task_deps {
TaskDepsRef::Ignore => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TaskDepsRef::Ignore",
::core::option::Option::Some(format_args!("expected no task dependency tracking")));
}
}
};assert_matches!(
253 task_deps,
254 TaskDepsRef::Ignore,
255"expected no task dependency tracking"
256);
257 })
258 }
259 }
260261pub fn assert_eval_always(&self) {
262if self.data.is_some() {
263read_deps(|deps| {
264{
match deps {
TaskDepsRef::EvalAlways => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TaskDepsRef::EvalAlways",
::core::option::Option::Some(format_args!("expected eval always context")));
}
}
}assert_matches!(deps, TaskDepsRef::EvalAlways, "expected eval always context")265 });
266 }
267 }
268269pub fn with_ignore<OP, R>(&self, op: OP) -> R
270where
271OP: FnOnce() -> R,
272 {
273with_deps(TaskDepsRef::Ignore, op)
274 }
275276/// Used to wrap the deserialization of a query result from disk,
277 /// This method enforces that no new `DepNodes` are created during
278 /// query result deserialization.
279 ///
280 /// Enforcing this makes the query dep graph simpler - all nodes
281 /// must be created during the query execution, and should be
282 /// created from inside the 'body' of a query (the implementation
283 /// provided by a particular compiler crate).
284 ///
285 /// Consider the case of three queries `A`, `B`, and `C`, where
286 /// `A` invokes `B` and `B` invokes `C`:
287 ///
288 /// `A -> B -> C`
289 ///
290 /// Suppose that decoding the result of query `B` required re-computing
291 /// the query `C`. If we did not create a fresh `TaskDeps` when
292 /// decoding `B`, we would still be using the `TaskDeps` for query `A`
293 /// (if we needed to re-execute `A`). This would cause us to create
294 /// a new edge `A -> C`. If this edge did not previously
295 /// exist in the `DepGraph`, then we could end up with a different
296 /// `DepGraph` at the end of compilation, even if there were no
297 /// meaningful changes to the overall program (e.g. a newline was added).
298 /// In addition, this edge might cause a subsequent compilation run
299 /// to try to force `C` before marking other necessary nodes green. If
300 /// `C` did not exist in the new compilation session, then we could
301 /// get an ICE. Normally, we would have tried (and failed) to mark
302 /// some other query green (e.g. `item_children`) which was used
303 /// to obtain `C`, which would prevent us from ever trying to force
304 /// a nonexistent `D`.
305 ///
306 /// It might be possible to enforce that all `DepNode`s read during
307 /// deserialization already exist in the previous `DepGraph`. In
308 /// the above example, we would invoke `D` during the deserialization
309 /// of `B`. Since we correctly create a new `TaskDeps` from the decoding
310 /// of `B`, this would result in an edge `B -> D`. If that edge already
311 /// existed (with the same `DepPathHash`es), then it should be correct
312 /// to allow the invocation of the query to proceed during deserialization
313 /// of a query result. We would merely assert that the dep-graph fragment
314 /// that would have been added by invoking `C` while decoding `B`
315 /// is equivalent to the dep-graph fragment that we already instantiated for B
316 /// (at the point where we successfully marked B as green).
317 ///
318 /// However, this would require additional complexity
319 /// in the query infrastructure, and is not currently needed by the
320 /// decoding of any query results. Should the need arise in the future,
321 /// we should consider extending the query system with this functionality.
322pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
323where
324OP: FnOnce() -> R,
325 {
326with_deps(TaskDepsRef::Forbid, op)
327 }
328329#[inline(always)]
330pub fn with_task<'tcx, OP, R>(
331&self,
332 dep_node: DepNode,
333 tcx: TyCtxt<'tcx>,
334 op: OP,
335 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
336 ) -> (R, DepNodeIndex)
337where
338OP: FnOnce() -> R,
339 {
340match self.data() {
341Some(data) => data.with_task(dep_node, tcx, op, hash_result),
342None => (op(), self.next_virtual_depnode_index()),
343 }
344 }
345346pub fn with_anon_task<'tcx, OP, R>(
347&self,
348 tcx: TyCtxt<'tcx>,
349 dep_kind: DepKind,
350 op: OP,
351 ) -> (R, DepNodeIndex)
352where
353OP: FnOnce() -> R,
354 {
355match self.data() {
356Some(data) => {
357let (result, index) = data.with_anon_task_inner(tcx, dep_kind, op);
358self.read_index(index);
359 (result, index)
360 }
361None => (op(), self.next_virtual_depnode_index()),
362 }
363 }
364}
365366impl DepGraphData {
367#[inline(always)]
368pub fn with_task<'tcx, OP, R>(
369&self,
370 dep_node: DepNode,
371 tcx: TyCtxt<'tcx>,
372 op: OP,
373 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
374 ) -> (R, DepNodeIndex)
375where
376OP: FnOnce() -> R,
377 {
378// If the following assertion triggers, it can have two reasons:
379 // 1. Something is wrong with DepNode creation, either here or
380 // in `DepGraph::try_mark_green()`.
381 // 2. Two distinct query keys get mapped to the same `DepNode`
382 // (see for example #48923).
383self.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
384::alloc::__export::must_use({
::alloc::fmt::format(format_args!("forcing query with already existing `DepNode`: {0:?}",
dep_node))
})format!("forcing query with already existing `DepNode`: {dep_node:?}")385 });
386387let (result, task_deps) = if tcx.is_eval_always(dep_node.kind) {
388 (with_deps(TaskDepsRef::EvalAlways, op), None)
389 } else {
390let task_deps = Lock::new(TaskDeps::new(
391#[cfg(debug_assertions)]
392Some(dep_node),
393 ));
394 (with_deps(TaskDepsRef::Allow(&task_deps), op), Some(task_deps.into_inner()))
395 };
396397let edges: &[DepNodeIndex] = task_deps.as_ref().map_or(&[], |deps| deps.edges());
398let dep_node_index =
399self.hash_result_and_alloc_node(tcx, dep_node, edges, &result, hash_result);
400if let Some(TaskDeps { reads: TaskReads::Recorded(recorder), .. }) = task_deps {
401recorder.release(&self.read_recorder_pool);
402 }
403404 (result, dep_node_index)
405 }
406407/// Executes something within an "anonymous" task, that is, a task the
408 /// `DepNode` of which is determined by the list of inputs it read from.
409 ///
410 /// NOTE: this does not actually count as a read of the DepNode here.
411 /// Using the result of this task without reading the DepNode will result
412 /// in untracked dependencies which may lead to ICEs as nodes are
413 /// incorrectly marked green.
414 ///
415 /// FIXME: This could perhaps return a `WithDepNode` to ensure that the
416 /// user of this function actually performs the read.
417fn with_anon_task_inner<'tcx, OP, R>(
418&self,
419 tcx: TyCtxt<'tcx>,
420 dep_kind: DepKind,
421 op: OP,
422 ) -> (R, DepNodeIndex)
423where
424OP: FnOnce() -> R,
425 {
426if true {
if !!tcx.is_eval_always(dep_kind) {
::core::panicking::panic("assertion failed: !tcx.is_eval_always(dep_kind)")
};
};debug_assert!(!tcx.is_eval_always(dep_kind));
427428let task_deps = Lock::new(TaskDeps::new(
429#[cfg(debug_assertions)]
430None,
431 ));
432let result = with_deps(TaskDepsRef::Allow(&task_deps), op);
433let task_deps = task_deps.into_inner();
434let reads = task_deps.edges();
435436let dep_node_index = match reads.len() {
4370 => {
438// Because the dep-node id of anon nodes is computed from the sets of its
439 // dependencies we already know what the ID of this dependency-less node is
440 // going to be (i.e. equal to the precomputed
441 // `SINGLETON_DEPENDENCYLESS_ANON_NODE`). As a consequence we can skip creating
442 // a `StableHasher` and sending the node through interning.
443DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE444 }
4451 => {
446// When there is only one dependency, don't bother creating a node.
447reads[0]
448 }
449_ => {
450// The dep node indices are hashed here instead of hashing the dep nodes of the
451 // dependencies. These indices may refer to different nodes per session, but this
452 // isn't a problem here because we that ensure the final dep node hash is per
453 // session only by combining it with the per session `anon_id_seed`. This hash only
454 // need to map the dependencies to a single value on a per session basis.
455let mut hasher = StableHasher::new();
456reads.hash(&mut hasher);
457458let target_dep_node = DepNode {
459 kind: dep_kind,
460// Fingerprint::combine() is faster than sending Fingerprint
461 // through the StableHasher (at least as long as StableHasher
462 // is so slow).
463key_fingerprint: self.current.anon_id_seed.combine(hasher.finish()).into(),
464 };
465466// The DepNodes generated by the process above are not unique. 2 queries could
467 // have exactly the same dependencies. However, deserialization does not handle
468 // duplicated nodes, so we do the deduplication here directly.
469 //
470 // As anonymous nodes are a small quantity compared to the full dep-graph, the
471 // memory impact of this `anon_node_to_index` map remains tolerable, and helps
472 // us avoid useless growth of the graph with almost-equivalent nodes.
473self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
474self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
475 })
476 }
477 };
478479if let TaskReads::Recorded(recorder) = task_deps.reads {
480recorder.release(&self.read_recorder_pool);
481 }
482483 (result, dep_node_index)
484 }
485486/// Intern the new `DepNode` with the dependencies up-to-now.
487fn hash_result_and_alloc_node<'tcx, R>(
488&self,
489 tcx: TyCtxt<'tcx>,
490 node: DepNode,
491 edges: &[DepNodeIndex],
492 result: &R,
493 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
494 ) -> DepNodeIndex {
495let hashing_timer = tcx.prof.incr_result_hashing();
496let current_fingerprint = hash_result.map(|hash_result| {
497tcx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
498 });
499let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
500hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
501dep_node_index502 }
503}
504505impl DepGraph {
506#[inline]
507pub fn read_index(&self, dep_node_index: DepNodeIndex) {
508if let Some(ref data) = self.data {
509read_deps(|task_deps| {
510let mut task_deps = match task_deps {
511 TaskDepsRef::Allow(deps) => deps.lock(),
512 TaskDepsRef::EvalAlways => {
513// We don't need to record dependencies of eval_always
514 // queries. They are re-evaluated unconditionally anyway.
515return;
516 }
517 TaskDepsRef::Ignore => return,
518 TaskDepsRef::Forbid => {
519// Reading is forbidden in this context. ICE with a useful error message.
520panic_on_forbidden_read(data, dep_node_index)
521 }
522 };
523let task_deps = &mut *task_deps;
524525if truecfg!(debug_assertions) {
526data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
527 }
528529let new_read = task_deps.reads.insert(dep_node_index, &data.read_recorder_pool);
530if new_read {
531#[cfg(debug_assertions)]
532{
533if let Some(target) = task_deps.node
534 && let Some(ref forbidden_edge) = data.current.forbidden_edge
535 {
536let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
537if forbidden_edge.test(&src, &target) {
538{
::core::panicking::panic_fmt(format_args!("forbidden edge {0:?} -> {1:?} created",
src, target));
}panic!("forbidden edge {:?} -> {:?} created", src, target)539 }
540 }
541 }
542 } else if truecfg!(debug_assertions) {
543data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
544 }
545 })
546 }
547 }
548549/// This encodes a side effect by creating a node with an unique index and associating
550 /// it with the node, for use in the next session.
551#[inline]
552pub fn record_diagnostic<'tcx>(&self, tcx: TyCtxt<'tcx>, diagnostic: &DiagInner) {
553if let Some(ref data) = self.data {
554read_deps(|task_deps| match task_deps {
555 TaskDepsRef::EvalAlways | TaskDepsRef::Ignore => return,
556 TaskDepsRef::Forbid | TaskDepsRef::Allow(..) => {
557let dep_node_index = data558 .encode_side_effect(tcx, QuerySideEffect::Diagnostic(diagnostic.clone()));
559self.read_index(dep_node_index);
560 }
561 })
562 }
563 }
564/// This forces a side effect node green by running its side effect. `prev_index` would
565 /// refer to a node created used `encode_side_effect` in the previous session.
566#[inline]
567pub fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
568if let Some(ref data) = self.data {
569data.force_side_effect(tcx, prev_index);
570 }
571 }
572573#[inline]
574pub fn encode_side_effect<'tcx>(
575&self,
576 tcx: TyCtxt<'tcx>,
577 side_effect: QuerySideEffect,
578 ) -> DepNodeIndex {
579if let Some(ref data) = self.data {
580data.encode_side_effect(tcx, side_effect)
581 } else {
582self.next_virtual_depnode_index()
583 }
584 }
585586/// Create a node when we force-feed a value into the query cache.
587 /// This is used to remove cycles during type-checking const generic parameters.
588 ///
589 /// As usual in the query system, we consider the current state of the calling query
590 /// only depends on the list of dependencies up to now. As a consequence, the value
591 /// that this query gives us can only depend on those dependencies too. Therefore,
592 /// it is sound to use the current dependency set for the created node.
593 ///
594 /// During replay, the order of the nodes is relevant in the dependency graph.
595 /// So the unchanged replay will mark the caller query before trying to mark this one.
596 /// If there is a change to report, the caller query will be re-executed before this one.
597 ///
598 /// FIXME: If the code is changed enough for this node to be marked before requiring the
599 /// caller's node, we suppose that those changes will be enough to mark this node red and
600 /// force a recomputation using the "normal" way.
601pub fn with_feed_task<'tcx, R>(
602&self,
603 node: DepNode,
604 tcx: TyCtxt<'tcx>,
605 result: &R,
606 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
607 format_value_fn: fn(&R) -> String,
608 ) -> DepNodeIndex {
609if let Some(data) = self.data.as_ref() {
610// The caller query has more dependencies than the node we are creating. We may
611 // encounter a case where this created node is marked as green, but the caller query is
612 // subsequently marked as red or recomputed. In this case, we will end up feeding a
613 // value to an existing node.
614 //
615 // For sanity, we still check that the loaded stable hash and the new one match.
616if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
617let dep_node_index = data.colors.current(prev_index);
618if let Some(dep_node_index) = dep_node_index {
619incremental_verify_ich(
620tcx,
621data,
622result,
623prev_index,
624hash_result,
625format_value_fn,
626 );
627628#[cfg(debug_assertions)]
629if hash_result.is_some() {
630data.current.record_edge(
631dep_node_index,
632node,
633data.prev_value_fingerprint_of(prev_index),
634 );
635 }
636637return dep_node_index;
638 }
639 }
640641// `read_deps` calls the closure exactly once, with the current task's deps.
642let mut reads = SmallVec::<[DepNodeIndex; SMALL_READS_MAX]>::new();
643read_deps(|task_deps| match task_deps {
644 TaskDepsRef::Allow(deps) => {
645reads = SmallVec::from_slice(deps.lock().edges());
646 }
647 TaskDepsRef::EvalAlways => {
648reads.push(DepNodeIndex::FOREVER_RED_NODE);
649 }
650 TaskDepsRef::Ignore => {}
651 TaskDepsRef::Forbid => {
652{
::core::panicking::panic_fmt(format_args!("Cannot summarize when dependencies are not recorded."));
}panic!("Cannot summarize when dependencies are not recorded.")653 }
654 });
655656data.hash_result_and_alloc_node(tcx, node, &reads, result, hash_result)
657 } else {
658// Incremental compilation is turned off. We just execute the task
659 // without tracking. We still provide a dep-node index that uniquely
660 // identifies the task so that we have a cheap way of referring to
661 // the query for self-profiling.
662self.next_virtual_depnode_index()
663 }
664 }
665}
666667impl DepGraphData {
668fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
669&self,
670 sess: &Session,
671 dep_node: &DepNode,
672 msg: impl FnOnce() -> S,
673 ) {
674if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
675let color = self.colors.get(prev_index);
676let ok = match color {
677 DepNodeColor::Unknown => true,
678 DepNodeColor::Red => false,
679 DepNodeColor::Green(..) => sess.opts.jobs.frontend.is_some(), // Other threads may mark this green
680};
681if !ok {
682{ ::core::panicking::panic_display(&msg()); }panic!("{}", msg())683 }
684 }
685 }
686687fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
688if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
689self.colors.get(prev_index)
690 } else {
691// This is a node that did not exist in the previous compilation session.
692DepNodeColor::Unknown693 }
694 }
695696/// Returns true if the given node has been marked as green during the
697 /// current compilation session. Used in various assertions
698#[inline]
699pub fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
700#[allow(non_exhaustive_omitted_patterns)] match self.colors.get(prev_index) {
DepNodeColor::Green(_) => true,
_ => false,
}matches!(self.colors.get(prev_index), DepNodeColor::Green(_))701 }
702703#[inline]
704pub fn prev_value_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
705self.previous.value_fingerprint_for_index(prev_index)
706 }
707708/// The number of incremental sessions in this graph's lineage, from
709 /// [`SerializedDepGraph::session_count`]. Advances by one per successful
710 /// session; a failed session does not commit a graph, so a re-run sees
711 /// the same count.
712#[inline]
713pub fn session_count(&self) -> u64 {
714self.previous.session_count()
715 }
716717#[inline]
718pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> &DepNode {
719self.previous.index_to_node(prev_index)
720 }
721722pub fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
723self.debug_loaded_from_disk.lock().insert(dep_node);
724 }
725726/// This encodes a side effect by creating a node with an unique index and associating
727 /// it with the node, for use in the next session.
728#[inline]
729fn encode_side_effect<'tcx>(
730&self,
731 tcx: TyCtxt<'tcx>,
732 side_effect: QuerySideEffect,
733 ) -> DepNodeIndex {
734// Use `send_new` so we get an unique index, even though the dep node is not.
735let dep_node_index = self.current.encoder.send_new(
736DepNode {
737 kind: DepKind::SideEffect,
738 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
739 },
740Fingerprint::ZERO,
741// We want the side effect node to always be red so it will be forced and run the
742 // side effect.
743&[DepNodeIndex::FOREVER_RED_NODE],
744 );
745tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
746dep_node_index747 }
748749/// This forces a side effect node green by running its side effect. `prev_index` would
750 /// refer to a node created used `encode_side_effect` in the previous session.
751#[inline]
752fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
753with_deps(TaskDepsRef::Ignore, || {
754let side_effect = tcx755 .query_system
756 .on_disk_cache
757 .as_ref()
758 .unwrap()
759 .load_side_effect(tcx, prev_index)
760 .unwrap();
761762// Use `send_and_color` as `promote_node_and_deps_to_current` expects all
763 // green dependencies. `send_and_color` will also prevent multiple nodes
764 // being encoded for concurrent calls.
765let dep_node_index = self.current.encoder.send_and_color(
766prev_index,
767&self.colors,
768DepNode {
769 kind: DepKind::SideEffect,
770 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
771 },
772Fingerprint::ZERO,
773&[DepNodeIndex::FOREVER_RED_NODE],
774true,
775 );
776777match &side_effect {
778 QuerySideEffect::Diagnostic(diagnostic) => {
779tcx.dcx().emit_diagnostic(diagnostic.clone());
780 }
781 QuerySideEffect::CheckFeature { symbol } => {
782tcx.query_system.used_features.lock().insert(*symbol, dep_node_index);
783 }
784 }
785786// This will just overwrite the same value for concurrent calls.
787tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
788 })
789 }
790791fn alloc_and_color_node(
792&self,
793 key: DepNode,
794 edges: &[DepNodeIndex],
795 value_fingerprint: Option<Fingerprint>,
796 ) -> DepNodeIndex {
797if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
798// Determine the color and index of the new `DepNode`.
799let is_green = if let Some(value_fingerprint) = value_fingerprint {
800if value_fingerprint == self.previous.value_fingerprint_for_index(prev_index) {
801// This is a green node: it existed in the previous compilation,
802 // its query was re-executed, and it has the same result as before.
803true
804} else {
805// This is a red node: it existed in the previous compilation, its query
806 // was re-executed, but it has a different result from before.
807false
808}
809 } else {
810// This is a red node, effectively: it existed in the previous compilation
811 // session, its query was re-executed, but it doesn't compute a result hash
812 // (i.e. it represents a `no_hash` query), so we have no way of determining
813 // whether or not the result was the same as before.
814false
815};
816817let value_fingerprint = value_fingerprint.unwrap_or(Fingerprint::ZERO);
818819let dep_node_index = self.current.encoder.send_and_color(
820prev_index,
821&self.colors,
822key,
823value_fingerprint,
824edges,
825is_green,
826 );
827828#[cfg(debug_assertions)]
829self.current.record_edge(dep_node_index, key, value_fingerprint);
830831dep_node_index832 } else {
833self.current.alloc_new_node(key, edges, value_fingerprint.unwrap_or(Fingerprint::ZERO))
834 }
835 }
836837fn promote_node_and_deps_to_current(
838&self,
839 prev_index: SerializedDepNodeIndex,
840 edges: &[DepNodeIndex],
841 ) -> Option<DepNodeIndex> {
842let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors, edges);
843844#[cfg(debug_assertions)]
845if let Some(dep_node_index) = dep_node_index {
846self.current.record_edge(
847dep_node_index,
848*self.previous.index_to_node(prev_index),
849self.previous.value_fingerprint_for_index(prev_index),
850 );
851 }
852853dep_node_index854 }
855}
856857impl DepGraph {
858/// Checks whether a previous work product exists for `v` and, if
859 /// so, return the path that leads to it. Used to skip doing work.
860pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
861self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
862 }
863864/// Access the map of work-products created during the cached run. Only
865 /// used during saving of the dep-graph.
866pub fn previous_work_products(&self) -> &WorkProductMap {
867&self.data.as_ref().unwrap().previous_work_products
868 }
869870pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
871self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
872 }
873874pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool {
875// We only check if we have a dep node corresponding to the given dep kind.
876#[allow(rustc::potential_query_instability)]
877self.data
878 .as_ref()
879 .unwrap()
880 .debug_loaded_from_disk
881 .lock()
882 .iter()
883 .any(|node| node.kind == dep_kind)
884 }
885886fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
887if let Some(ref data) = self.data {
888return data.node_color(dep_node);
889 }
890891 DepNodeColor::Unknown892 }
893894pub fn try_mark_green<'tcx>(
895&self,
896 tcx: TyCtxt<'tcx>,
897 dep_node: &DepNode,
898 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
899self.data()?.try_mark_green(tcx, dep_node)
900 }
901}
902903impl DepGraphData {
904/// Try to mark a node index for the node dep_node.
905 ///
906 /// A node will have an index, when it's already been marked green, or when we can mark it
907 /// green. This function will mark the current task as a reader of the specified node, when
908 /// a node index can be found for that node.
909pub fn try_mark_green<'tcx>(
910&self,
911 tcx: TyCtxt<'tcx>,
912 dep_node: &DepNode,
913 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
914if true {
if !!tcx.is_eval_always(dep_node.kind) {
::core::panicking::panic("assertion failed: !tcx.is_eval_always(dep_node.kind)")
};
};debug_assert!(!tcx.is_eval_always(dep_node.kind));
915916// Return None if the dep node didn't exist in the previous session
917let prev_index = self.previous.node_to_index_opt(dep_node)?;
918919if true {
{
match (&self.previous.index_to_node(prev_index), &dep_node) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.previous.index_to_node(prev_index), dep_node);
920921match self.colors.get(prev_index) {
922 DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
923 DepNodeColor::Red => None,
924 DepNodeColor::Unknown => {
925// This DepNode and the corresponding query invocation existed
926 // in the previous compilation session too, so we can try to
927 // mark it as green by recursively marking all of its
928 // dependencies green.
929930 // Reuse a per-worker buffer for the edges instead of allocating one per call.
931 // The recursion gives it back empty: each `EdgeFrame` pops its edges on drop.
932let mut edge_buf = self.green_edge_buf.take();
933let result = self.try_mark_previous_green(tcx, prev_index, None, &mut edge_buf);
934if true {
if !edge_buf.is_empty() {
::core::panicking::panic("assertion failed: edge_buf.is_empty()")
};
};debug_assert!(edge_buf.is_empty());
935self.green_edge_buf.set(edge_buf);
936result.map(|dep_node_index| (prev_index, dep_node_index))
937 }
938 }
939 }
940941/// Try to mark a dep-node which existed in the previous compilation session as green.
942{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_mark_previous_green",
"rustc_middle::dep_graph::graph", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_middle/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(942u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_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: Option<DepNodeIndex> = loop {};
return __tracing_attr_fake_return;
}
{
let mut edges = EdgeFrame::new(edge_buf);
let frame =
MarkFrame { index: prev_dep_node_index, parent: frame };
if true {
if !!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)
{
::core::panicking::panic("assertion failed: !tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)")
};
};
for parent_dep_node_index in
self.previous.edge_targets_from(prev_dep_node_index) {
match self.colors.get(parent_dep_node_index) {
DepNodeColor::Green(parent_index) => {
edges.push(parent_index);
continue;
}
DepNodeColor::Red => return None,
DepNodeColor::Unknown => {}
}
let parent_dep_node =
self.previous.index_to_node(parent_dep_node_index);
if !tcx.is_eval_always(parent_dep_node.kind) &&
let Some(parent_index) =
self.try_mark_previous_green(tcx, parent_dep_node_index,
Some(&frame), edges.buf) {
edges.push(parent_index);
continue;
}
if !tcx.try_force_from_dep_node(*parent_dep_node,
parent_dep_node_index, &frame) {
return None;
}
match self.colors.get(parent_dep_node_index) {
DepNodeColor::Green(parent_index) => {
edges.push(parent_index);
continue;
}
DepNodeColor::Red => return None,
DepNodeColor::Unknown => {}
}
if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
{
::core::panicking::panic_fmt(format_args!("try_mark_previous_green() - forcing failed to set a color"));
};
}
return None;
}
let dep_node_index =
self.promote_node_and_deps_to_current(prev_dep_node_index,
edges.get())?;
Some(dep_node_index)
}
}
}#[instrument(skip(self, tcx, prev_dep_node_index, frame, edge_buf), level = "debug")]943fn try_mark_previous_green<'tcx>(
944&self,
945 tcx: TyCtxt<'tcx>,
946 prev_dep_node_index: SerializedDepNodeIndex,
947 frame: Option<&MarkFrame<'_>>,
948// Amortized buffer to store edges in.
949edge_buf: &mut Vec<DepNodeIndex>,
950 ) -> Option<DepNodeIndex> {
951let mut edges = EdgeFrame::new(edge_buf);
952let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
953954// We never try to mark eval_always nodes as green
955debug_assert!(!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind));
956957for parent_dep_node_index in self.previous.edge_targets_from(prev_dep_node_index) {
958match self.colors.get(parent_dep_node_index) {
959// This dependency has been marked as green before, we are still ok and can
960 // continue checking the remaining dependencies.
961DepNodeColor::Green(parent_index) => {
962 edges.push(parent_index);
963continue;
964 }
965966// This dependency's result is different to the previous compilation session. We
967 // cannot mark this dep_node as green, so stop checking.
968DepNodeColor::Red => return None,
969970// We still need to determine this dependency's colour.
971DepNodeColor::Unknown => {}
972 }
973974let parent_dep_node = self.previous.index_to_node(parent_dep_node_index);
975976// If this dependency isn't eval_always, try to mark it green recursively.
977if !tcx.is_eval_always(parent_dep_node.kind)
978 && let Some(parent_index) = self.try_mark_previous_green(
979 tcx,
980 parent_dep_node_index,
981Some(&frame),
982// Pass the edge buffer to the recursive call.
983 // It will use an `EdgeFrame` to give it back unchanged.
984edges.buf,
985 )
986 {
987 edges.push(parent_index);
988continue;
989 }
990991// We failed to mark it green, so we try to force the query.
992if !tcx.try_force_from_dep_node(*parent_dep_node, parent_dep_node_index, &frame) {
993return None;
994 }
995996match self.colors.get(parent_dep_node_index) {
997 DepNodeColor::Green(parent_index) => {
998 edges.push(parent_index);
999continue;
1000 }
1001 DepNodeColor::Red => return None,
1002 DepNodeColor::Unknown => {}
1003 }
10041005if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
1006panic!("try_mark_previous_green() - forcing failed to set a color");
1007 }
10081009// If the query we just forced has resulted in some kind of compilation error, we
1010 // cannot rely on the dep-node color having been properly updated. This means that the
1011 // query system has reached an invalid state. We let the compiler continue (by
1012 // returning `None`) so it can emit error messages and wind down, but rely on the fact
1013 // that this invalid state will not be persisted to the incremental compilation cache
1014 // because of compilation errors being present.
1015return None;
1016 }
10171018// If we got here without hitting a `return` that means that all
1019 // dependencies of this DepNode could be marked as green. Therefore we
1020 // can also mark this DepNode as green.
10211022 // There may be multiple threads trying to mark the same dep node green concurrently.
10231024 // We allocating an entry for the node in the current dependency graph and
1025 // adding all the appropriate edges imported from the previous graph.
1026 //
1027 // `no_hash` nodes may fail this promotion due to already being conservatively colored red.
1028let dep_node_index =
1029self.promote_node_and_deps_to_current(prev_dep_node_index, edges.get())?;
10301031// ... and finally storing a "Green" entry in the color map.
1032 // Multiple threads can all write the same color here.
10331034Some(dep_node_index)
1035 }
1036}
10371038impl DepGraph {
1039/// Returns true if the given node has been marked as red during the
1040 /// current compilation session. Used in various assertions
1041pub fn is_red(&self, dep_node: &DepNode) -> bool {
1042#[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
DepNodeColor::Red => true,
_ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Red)1043 }
10441045/// Returns true if the given node has been marked as green during the
1046 /// current compilation session. Used in various assertions
1047pub fn is_green(&self, dep_node: &DepNode) -> bool {
1048#[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
DepNodeColor::Green(_) => true,
_ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Green(_))1049 }
10501051pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
1052&self,
1053 sess: &Session,
1054 dep_node: &DepNode,
1055 msg: impl FnOnce() -> S,
1056 ) {
1057if let Some(data) = &self.data {
1058data.assert_dep_node_not_yet_allocated_in_current_session(sess, dep_node, msg)
1059 }
1060 }
10611062/// This method loads all on-disk cacheable query results into memory, so
1063 /// they can be written out to the new cache file again. Most query results
1064 /// will already be in memory but in the case where we marked something as
1065 /// green but then did not need the value, that value will never have been
1066 /// loaded from disk.
1067 ///
1068 /// This method will only load queries that will end up in the disk cache.
1069 /// Other queries will not be executed.
1070pub fn exec_cache_promotions<'tcx>(&self, tcx: TyCtxt<'tcx>) {
1071let _prof_timer = tcx.prof.generic_activity("incr_comp_query_cache_promotion");
10721073let data = self.data.as_ref().unwrap();
1074for prev_index in data.colors.values.indices() {
1075match data.colors.get(prev_index) {
1076 DepNodeColor::Green(dep_node_index) => {
1077let dep_node = data.previous.index_to_node(prev_index);
1078if let Some(promote_fn) =
1079 tcx.dep_kind_vtable(dep_node.kind).promote_from_disk_fn
1080 {
1081 promote_fn(tcx, *dep_node, prev_index, dep_node_index)
1082 };
1083 }
1084 DepNodeColor::Unknown | DepNodeColor::Red => {
1085// We can skip red nodes because a node can only be marked
1086 // as red if the query result was recomputed and thus is
1087 // already in memory.
1088}
1089 }
1090 }
1091 }
10921093pub(crate) fn finish_encoding(&self) -> FileEncodeResult {
1094if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1095 }
10961097pub fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1098if true {
if !self.data.is_none() {
::core::panicking::panic("assertion failed: self.data.is_none()")
};
};debug_assert!(self.data.is_none());
1099let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1100DepNodeIndex::from_u32(index)
1101 }
1102}
11031104/// A "work product" is an intermediate result that we save into the
1105/// incremental directory for later re-use. The primary example are
1106/// the object files that we save for each partition at code
1107/// generation time.
1108///
1109/// Each work product is associated with a dep-node, representing the
1110/// process that produced the work-product. If that dep-node is found
1111/// to be dirty when we load up, then we will delete the work-product
1112/// at load time. If the work-product is found to be clean, then we
1113/// will keep a record in the `previous_work_products` list.
1114///
1115/// In addition, work products have an associated hash. This hash is
1116/// an extra hash that can be used to decide if the work-product from
1117/// a previous compilation can be re-used (in addition to the dirty
1118/// edges check).
1119///
1120/// As the primary example, consider the object files we generate for
1121/// each partition. In the first run, we create partitions based on
1122/// the symbols that need to be compiled. For each partition P, we
1123/// hash the symbols in P and create a `WorkProduct` record associated
1124/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1125/// in P.
1126///
1127/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1128/// judged to be clean (which means none of the things we read to
1129/// generate the partition were found to be dirty), it will be loaded
1130/// into previous work products. We will then regenerate the set of
1131/// symbols in the partition P and hash them (note that new symbols
1132/// may be added -- for example, new monomorphizations -- even if
1133/// nothing in P changed!). We will compare that hash against the
1134/// previous hash. If it matches up, we can reuse the object file.
1135#[derive(#[automatically_derived]
impl ::core::clone::Clone for WorkProduct {
#[inline]
fn clone(&self) -> WorkProduct {
WorkProduct {
cgu_name: ::core::clone::Clone::clone(&self.cgu_name),
saved_files: ::core::clone::Clone::clone(&self.saved_files),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WorkProduct {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "WorkProduct",
"cgu_name", &self.cgu_name, "saved_files", &&self.saved_files)
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for WorkProduct {
fn encode(&self, __encoder: &mut __E) {
let WorkProduct {
cgu_name: ref __binding_0, saved_files: ref __binding_1 } =
*self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for WorkProduct {
fn decode(__decoder: &mut __D) -> Self {
WorkProduct {
cgu_name: ::rustc_serialize::Decodable::decode(__decoder),
saved_files: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
1136pub struct WorkProduct {
1137pub cgu_name: String,
1138/// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1139 /// saved file and the key is some identifier for the type of file being saved.
1140 ///
1141 /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1142 /// the object file's path, and "dwo" to the dwarf object file's path.
1143pub saved_files: UnordMap<String, String>,
1144}
11451146pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
11471148// Index type for `DepNodeData`'s edges.
1149#[automatically_derived]
impl ::core::marker::Copy for EdgeIndex { }
impl EdgeIndex {
#[doc = r" Maximum value the index can take, as a `u32`."]
const MAX_AS_U32: u32 = 0xFFFF_FF00;
#[doc = r" Maximum value the index can take."]
const MAX: Self = Self::from_u32(0xFFFF_FF00);
#[doc = r" Zero value of the index."]
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]
const fn from_usize(value: usize) -> Self {
if !(value <= (0xFFFF_FF00 as usize)) {
::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 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]
const fn from_u32(value: u32) -> Self {
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
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]
const fn from_u16(value: u16) -> Self {
let value = value as u32;
if !(value <= 0xFFFF_FF00) {
::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
};
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]
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]
const fn index(self) -> usize { self.as_usize() }
#[doc = r" Extracts the value of this index as a `u32`."]
#[inline]
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]
const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for EdgeIndex {
type Output = Self;
#[inline]
fn add(self, other: usize) -> Self {
Self::from_usize(self.index() + other)
}
}
impl std::ops::AddAssign<usize> for EdgeIndex {
#[inline]
fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for EdgeIndex {
#[inline]
fn new(value: usize) -> Self { Self::from_usize(value) }
#[inline]
fn index(self) -> usize { self.as_usize() }
}
impl From<EdgeIndex> for u32 {
#[inline]
fn from(v: EdgeIndex) -> u32 { v.as_u32() }
}
impl From<EdgeIndex> for usize {
#[inline]
fn from(v: EdgeIndex) -> usize { v.as_usize() }
}
impl From<usize> for EdgeIndex {
#[inline]
fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for EdgeIndex {
#[inline]
fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for EdgeIndex {}
impl ::std::cmp::PartialEq for EdgeIndex {
fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for EdgeIndex {}
impl ::std::hash::Hash for EdgeIndex {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.as_u32().hash(state)
}
}
impl ::std::fmt::Debug for EdgeIndex {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_fmt(format_args!("{0}", self.as_u32()))
}
}rustc_index::newtype_index! {
1150struct EdgeIndex {}
1151}11521153/// `CurrentDepGraph` stores the dependency graph for the current session. It
1154/// will be populated as we run queries or tasks. We never remove nodes from the
1155/// graph: they are only added.
1156///
1157/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1158/// in memory. This is important, because these graph structures are some of the
1159/// largest in the compiler.
1160///
1161/// For this reason, we avoid storing `DepNode`s more than once as map
1162/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1163/// graph, and we map nodes in the previous graph to indices via a two-step
1164/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1165/// and the `prev_index_to_index` vector (which is more compact and faster than
1166/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1167///
1168/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1169/// and `prev_index_to_index` fields are locked separately. Operations that take
1170/// a `DepNodeIndex` typically just access the `data` field.
1171///
1172/// We only need to manipulate at most two locks simultaneously:
1173/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1174/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1175/// first, and `data` second.
1176pub(super) struct CurrentDepGraph {
1177 encoder: GraphEncoder,
1178 anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
11791180/// This is used to verify that value fingerprints do not change between the
1181 /// creation of a node and its recomputation.
1182#[cfg(debug_assertions)]
1183value_fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
11841185/// Used to trap when a specific edge is added to the graph.
1186 /// This is used for debug purposes and is only active with `debug_assertions`.
1187#[cfg(debug_assertions)]
1188forbidden_edge: Option<EdgeFilter>,
11891190/// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1191 /// their edges. This has the beneficial side-effect that multiple anonymous
1192 /// nodes can be coalesced into one without changing the semantics of the
1193 /// dependency graph. However, the merging of nodes can lead to a subtle
1194 /// problem during red-green marking: The color of an anonymous node from
1195 /// the current session might "shadow" the color of the node with the same
1196 /// ID from the previous session. In order to side-step this problem, we make
1197 /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1198 /// This is implemented by mixing a session-key into the ID fingerprint of
1199 /// each anon node. The session-key is a hash of the number of previous sessions.
1200anon_id_seed: Fingerprint,
12011202/// These are simple counters that are for profiling and
1203 /// debugging and only active with `debug_assertions`.
1204pub(super) total_read_count: AtomicU64,
1205pub(super) total_duplicate_read_count: AtomicU64,
1206}
12071208impl CurrentDepGraph {
1209fn new(
1210 session: &Session,
1211 prev_index_space_len: usize,
1212 encoder: FileEncoder<'static>,
1213 previous: Arc<SerializedDepGraph>,
1214 ) -> Self {
1215let mut stable_hasher = StableHasher::new();
1216previous.session_count().hash(&mut stable_hasher);
1217let anon_id_seed = stable_hasher.finish();
12181219#[cfg(debug_assertions)]
1220let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1221Ok(s) => match EdgeFilter::new(&s) {
1222Ok(f) => Some(f),
1223Err(err) => {
::core::panicking::panic_fmt(format_args!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {0}",
err));
}panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1224 },
1225Err(_) => None,
1226 };
12271228let new_node_count_estimate = 102 * previous.live_node_count() / 100 + 200;
12291230CurrentDepGraph {
1231 encoder: GraphEncoder::new(session, encoder, prev_index_space_len, previous),
1232 anon_node_to_index: ShardedHashMap::with_capacity(
12333 * new_node_count_estimate / 100, // Reserve capacity for 3% anon nodes
1234),
1235anon_id_seed,
1236#[cfg(debug_assertions)]
1237forbidden_edge,
1238#[cfg(debug_assertions)]
1239value_fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1240 total_read_count: AtomicU64::new(0),
1241 total_duplicate_read_count: AtomicU64::new(0),
1242 }
1243 }
12441245#[cfg(debug_assertions)]
1246fn record_edge(
1247&self,
1248 dep_node_index: DepNodeIndex,
1249 key: DepNode,
1250 value_fingerprint: Fingerprint,
1251 ) {
1252if let Some(forbidden_edge) = &self.forbidden_edge {
1253forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1254 }
1255let prior_value_fingerprint = *self1256 .value_fingerprints
1257 .lock()
1258 .get_or_insert_with(dep_node_index, || value_fingerprint);
1259{
match (&prior_value_fingerprint, &value_fingerprint) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("Unstable fingerprints for {0:?}",
key)));
}
}
}
};assert_eq!(prior_value_fingerprint, value_fingerprint, "Unstable fingerprints for {key:?}");
1260 }
12611262/// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1263 /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1264#[inline(always)]
1265fn alloc_new_node(
1266&self,
1267 key: DepNode,
1268 edges: &[DepNodeIndex],
1269 value_fingerprint: Fingerprint,
1270 ) -> DepNodeIndex {
1271let dep_node_index = self.encoder.send_new(key, value_fingerprint, edges);
12721273#[cfg(debug_assertions)]
1274self.record_edge(dep_node_index, key, value_fingerprint);
12751276dep_node_index1277 }
1278}
12791280#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for TaskDepsRef<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TaskDepsRef::Allow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
&__self_0),
TaskDepsRef::EvalAlways =>
::core::fmt::Formatter::write_str(f, "EvalAlways"),
TaskDepsRef::Ignore =>
::core::fmt::Formatter::write_str(f, "Ignore"),
TaskDepsRef::Forbid =>
::core::fmt::Formatter::write_str(f, "Forbid"),
}
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'a> ::core::clone::TrivialClone for TaskDepsRef<'a> { }
#[automatically_derived]
impl<'a> ::core::clone::Clone for TaskDepsRef<'a> {
#[inline]
fn clone(&self) -> TaskDepsRef<'a> {
let _: ::core::clone::AssertParamIsClone<&'a Lock<TaskDeps>>;
*self
}
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for TaskDepsRef<'a> { }Copy)]
1281pub enum TaskDepsRef<'a> {
1282/// New dependencies can be added to the
1283 /// `TaskDeps`. This is used when executing a 'normal' query
1284 /// (no `eval_always` modifier)
1285Allow(&'a Lock<TaskDeps>),
1286/// This is used when executing an `eval_always` query. We don't
1287 /// need to track dependencies for a query that's always
1288 /// re-executed -- but we need to know that this is an `eval_always`
1289 /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1290 /// when directly feeding other queries.
1291EvalAlways,
1292/// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1293Ignore,
1294/// Any attempt to add new dependencies will cause a panic.
1295 /// This is used when decoding a query result from disk,
1296 /// to ensure that the decoding process doesn't itself
1297 /// require the execution of any queries.
1298Forbid,
1299}
13001301#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TaskDeps {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "TaskDeps",
"node", &self.node, "reads", &&self.reads)
}
}Debug)]
1302pub struct TaskDeps {
1303#[cfg(debug_assertions)]
1304node: Option<DepNode>,
13051306 reads: TaskReads,
1307}
13081309impl TaskDeps {
1310#[inline]
1311fn new(#[cfg(debug_assertions)] node: Option<DepNode>) -> Self {
1312TaskDeps {
1313#[cfg(debug_assertions)]
1314node,
1315 reads: TaskReads::new(),
1316 }
1317 }
13181319/// The task's deduplicated reads, in first-read order.
1320#[inline]
1321fn edges(&self) -> &[DepNodeIndex] {
1322self.reads.edges()
1323 }
1324}
13251326// A data structure that stores Option<DepNodeColor> values as a contiguous
1327// array, using one u32 per entry.
1328pub(super) struct DepNodeColorMap {
1329 values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1330}
13311332// All values below `COMPRESSED_RED` are green.
1333const COMPRESSED_RED: u32 = u32::MAX - 1;
1334const COMPRESSED_UNKNOWN: u32 = u32::MAX;
13351336impl DepNodeColorMap {
1337fn new(size: usize) -> DepNodeColorMap {
1338if true {
if !(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32) {
::core::panicking::panic("assertion failed: COMPRESSED_RED > DepNodeIndex::MAX_AS_U32")
};
};debug_assert!(COMPRESSED_RED > DepNodeIndex::MAX_AS_U32);
1339DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1340 }
13411342#[inline]
1343pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1344let value = self.values[index].load(Ordering::Relaxed);
1345if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1346 }
13471348/// Atomically sets the color of a previous-session dep node to either green
1349 /// or red, if it has not already been colored.
1350 ///
1351 /// If the node already has a color, the new color is ignored, and the
1352 /// return value indicates the existing color.
1353#[inline(always)]
1354pub(super) fn try_set_color(
1355&self,
1356 prev_index: SerializedDepNodeIndex,
1357 color: DesiredColor,
1358 ) -> TrySetColorResult {
1359match self.values[prev_index].compare_exchange(
1360COMPRESSED_UNKNOWN,
1361match color {
1362 DesiredColor::Red => COMPRESSED_RED,
1363 DesiredColor::Green { index } => index.as_u32(),
1364 },
1365 Ordering::Relaxed,
1366 Ordering::Relaxed,
1367 ) {
1368Ok(_) => TrySetColorResult::Success,
1369Err(COMPRESSED_RED) => TrySetColorResult::AlreadyRed,
1370Err(index) => TrySetColorResult::AlreadyGreen { index: DepNodeIndex::from_u32(index) },
1371 }
1372 }
13731374#[inline]
1375pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1376let value = self.values[index].load(Ordering::Acquire);
1377// Green is by far the most common case. Check for that first so we can succeed with a
1378 // single comparison.
1379if value < COMPRESSED_RED {
1380 DepNodeColor::Green(DepNodeIndex::from_u32(value))
1381 } else if value == COMPRESSED_RED {
1382 DepNodeColor::Red1383 } else {
1384if true {
{
match (&value, &COMPRESSED_UNKNOWN) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(value, COMPRESSED_UNKNOWN);
1385 DepNodeColor::Unknown1386 }
1387 }
1388}
13891390/// The color that [`DepNodeColorMap::try_set_color`] should try to apply to a node.
1391#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DesiredColor { }
#[automatically_derived]
impl ::core::clone::Clone for DesiredColor {
#[inline]
fn clone(&self) -> DesiredColor {
let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DesiredColor { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for DesiredColor {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DesiredColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
DesiredColor::Green { index: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Green",
"index", &__self_0),
}
}
}Debug)]
1392pub(super) enum DesiredColor {
1393/// Try to mark the node red.
1394Red,
1395/// Try to mark the node green, associating it with a current-session node index.
1396Green { index: DepNodeIndex },
1397}
13981399/// Return value of [`DepNodeColorMap::try_set_color`], indicating success or failure,
1400/// and (on failure) what the existing color is.
1401#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TrySetColorResult { }
#[automatically_derived]
impl ::core::clone::Clone for TrySetColorResult {
#[inline]
fn clone(&self) -> TrySetColorResult {
let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrySetColorResult { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for TrySetColorResult {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TrySetColorResult::Success =>
::core::fmt::Formatter::write_str(f, "Success"),
TrySetColorResult::AlreadyRed =>
::core::fmt::Formatter::write_str(f, "AlreadyRed"),
TrySetColorResult::AlreadyGreen { index: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AlreadyGreen", "index", &__self_0),
}
}
}Debug)]
1402pub(super) enum TrySetColorResult {
1403/// The [`DesiredColor`] was freshly applied to the node.
1404Success,
1405/// Coloring failed because the node was already marked red.
1406AlreadyRed,
1407/// Coloring failed because the node was already marked green,
1408 /// and corresponds to node `index` in the current-session dep graph.
1409AlreadyGreen { index: DepNodeIndex },
1410}
14111412#[inline(never)]
1413#[cold]
1414pub(crate) fn print_markframe_trace(graph: &DepGraph, frame: &MarkFrame<'_>) {
1415let data = graph.data.as_ref().unwrap();
14161417{
::std::io::_eprint(format_args!("there was a panic while trying to force a dep node\n"));
};eprintln!("there was a panic while trying to force a dep node");
1418{ ::std::io::_eprint(format_args!("try_mark_green dep node stack:\n")); };eprintln!("try_mark_green dep node stack:");
14191420let mut i = 0;
1421let mut current = Some(frame);
1422while let Some(frame) = current {
1423let node = data.previous.index_to_node(frame.index);
1424{ ::std::io::_eprint(format_args!("#{0} {1:?}\n", i, node)); };eprintln!("#{i} {node:?}");
1425 current = frame.parent;
1426 i += 1;
1427 }
14281429{
::std::io::_eprint(format_args!("end of try_mark_green dep node stack\n"));
};eprintln!("end of try_mark_green dep node stack");
1430}
14311432#[cold]
1433#[inline(never)]
1434fn panic_on_forbidden_read(data: &DepGraphData, dep_node_index: DepNodeIndex) -> ! {
1435// We have to do an expensive reverse-lookup of the DepNode that
1436 // corresponds to `dep_node_index`, but that's OK since we are about
1437 // to ICE anyway.
1438let mut dep_node = None;
14391440// First try to find the dep node among those that already existed in the
1441 // previous session and has been marked green
1442for prev_index in data.colors.values.indices() {
1443if data.colors.current(prev_index) == Some(dep_node_index) {
1444 dep_node = Some(*data.previous.index_to_node(prev_index));
1445break;
1446 }
1447 }
14481449let dep_node = dep_node.map_or_else(
1450 || ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("with index {0:?}", dep_node_index))
})format!("with index {:?}", dep_node_index),
1451 |dep_node| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0:?}`", dep_node))
})format!("`{:?}`", dep_node),
1452 );
14531454{
::core::panicking::panic_fmt(format_args!("Error: trying to record dependency on DepNode {0} in a context that does not allow it (e.g. during query deserialization). The most common case of recording a dependency on a DepNode `foo` is when the corresponding query `foo` is invoked. Invoking queries is not allowed as part of loading something from the incremental on-disk cache. See <https://github.com/rust-lang/rust/pull/91919>.",
dep_node));
}panic!(
1455"Error: trying to record dependency on DepNode {dep_node} in a \
1456 context that does not allow it (e.g. during query deserialization). \
1457 The most common case of recording a dependency on a DepNode `foo` is \
1458 when the corresponding query `foo` is invoked. Invoking queries is not \
1459 allowed as part of loading something from the incremental on-disk cache. \
1460 See <https://github.com/rust-lang/rust/pull/91919>."
1461)1462}
14631464impl<'tcx> TyCtxt<'tcx> {
1465/// Return whether this kind always require evaluation.
1466#[inline(always)]
1467fn is_eval_always(self, kind: DepKind) -> bool {
1468self.dep_kind_vtable(kind).is_eval_always
1469 }
1470}