1use std::assert_matches;
2use std::fmt::Debug;
3use std::hash::Hash;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU32, Ordering};
67use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint};
8use rustc_data_structures::fx::FxHashSet;
9use rustc_data_structures::profiling::QueryInvocationId;
10use rustc_data_structures::sharded::{self, ShardedHashMap};
11use rustc_data_structures::stable_hash::{StableHash, StableHasher};
12use rustc_data_structures::sync::{AtomicU64, Lock};
13use rustc_data_structures::unord::UnordMap;
14use rustc_errors::DiagInner;
15use rustc_index::IndexVec;
16use rustc_macros::{Decodable, Encodable};
17use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
18use rustc_session::Session;
19use rustc_span::Symbol;
20use tracing::instrument;
21#[cfg(debug_assertions)]
22use {super::debug::EdgeFilter, std::env};
2324use super::retained::RetainedDepGraph;
25use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex};
26use super::{DepKind, DepNode, WorkProductId, read_deps, with_deps};
27use crate::dep_graph::edges::EdgesVec;
28use crate::ich::StableHashState;
29use crate::ty::TyCtxt;
30use crate::verify_ich::incremental_verify_ich;
3132/// Tracks 'side effects' for a particular query.
33/// This struct is saved to disk along with the query result,
34/// and loaded from disk if we mark the query as green.
35/// This allows us to 'replay' changes to global state
36/// that would otherwise only occur if we actually
37/// executed the query method.
38///
39/// Each side effect gets an unique dep node index which is added
40/// as a dependency of the query which had the effect.
41#[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)]
42pub enum QuerySideEffect {
43/// Stores a diagnostic emitted during query execution.
44 /// This diagnostic will be re-emitted if we mark
45 /// the query as green, as that query will have the side
46 /// effect dep node as a dependency.
47Diagnostic(DiagInner),
48/// Records the feature used during query execution.
49 /// This feature will be inserted into `sess.used_features`
50 /// if we mark the query as green, as that query will have
51 /// the side effect dep node as a dependency.
52CheckFeature { symbol: Symbol },
53}
5455#[derive(#[automatically_derived]
impl ::core::clone::Clone for DepGraph {
#[inline]
fn clone(&self) -> DepGraph {
DepGraph {
data: ::core::clone::Clone::clone(&self.data),
virtual_dep_node_index: ::core::clone::Clone::clone(&self.virtual_dep_node_index),
}
}
}Clone)]
56pub struct DepGraph {
57 data: Option<Arc<DepGraphData>>,
5859/// This field is used for assigning DepNodeIndices when running in
60 /// non-incremental mode. Even in non-incremental mode we make sure that
61 /// each task has a `DepNodeIndex` that uniquely identifies it. This unique
62 /// ID is used for self-profiling.
63virtual_dep_node_index: Arc<AtomicU32>,
64}
6566impl ::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! {
67pub struct DepNodeIndex {}
68}6970// We store a large collection of these in `prev_index_to_index` during
71// non-full incremental builds, and want to ensure that the element size
72// doesn't inadvertently increase.
73const _: [(); 4] = [(); ::std::mem::size_of::<Option<DepNodeIndex>>()];rustc_data_structures::static_assert_size!(Option<DepNodeIndex>, 4);
7475impl DepNodeIndex {
76const SINGLETON_ZERO_DEPS_ANON_NODE: DepNodeIndex = DepNodeIndex::ZERO;
77pub const FOREVER_RED_NODE: DepNodeIndex = DepNodeIndex::from_u32(1);
78}
7980impl From<DepNodeIndex> for QueryInvocationId {
81#[inline(always)]
82fn from(dep_node_index: DepNodeIndex) -> Self {
83QueryInvocationId(dep_node_index.as_u32())
84 }
85}
8687pub(crate) struct MarkFrame<'a> {
88 index: SerializedDepNodeIndex,
89 parent: Option<&'a MarkFrame<'a>>,
90}
9192#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DepNodeColor {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DepNodeColor::Green(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Green",
&__self_0),
DepNodeColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
DepNodeColor::Unknown =>
::core::fmt::Formatter::write_str(f, "Unknown"),
}
}
}Debug)]
93pub(super) enum DepNodeColor {
94 Green(DepNodeIndex),
95 Red,
96 Unknown,
97}
9899pub struct DepGraphData {
100/// The new encoding of the dependency graph, optimized for red/green
101 /// tracking. The `current` field is the dependency graph of only the
102 /// current compilation session: We don't merge the previous dep-graph into
103 /// current one anymore, but we do reference shared data to save space.
104current: CurrentDepGraph,
105106/// The dep-graph from the previous compilation session. It contains all
107 /// nodes and edges as well as all fingerprints of nodes that have them.
108previous: Arc<SerializedDepGraph>,
109110 colors: DepNodeColorMap,
111112/// When we load, there may be `.o` files, cached MIR, or other such
113 /// things available to us. If we find that they are not dirty, we
114 /// load the path to the file storing those work-products here into
115 /// this map. We can later look for and extract that data.
116previous_work_products: WorkProductMap,
117118/// Used by incremental compilation tests to assert that
119 /// a particular query result was decoded from disk
120 /// (not just marked green)
121debug_loaded_from_disk: Lock<FxHashSet<DepNode>>,
122}
123124pub fn hash_result<R>(hcx: &mut StableHashState<'_>, result: &R) -> Fingerprint125where
126R: StableHash,
127{
128let mut stable_hasher = StableHasher::new();
129result.stable_hash(hcx, &mut stable_hasher);
130stable_hasher.finish()
131}
132133impl DepGraph {
134pub fn new(
135 session: &Session,
136 prev_graph: Arc<SerializedDepGraph>,
137 prev_work_products: WorkProductMap,
138 encoder: FileEncoder,
139 ) -> DepGraph {
140let prev_graph_node_count = prev_graph.node_count();
141142let current =
143CurrentDepGraph::new(session, prev_graph_node_count, encoder, Arc::clone(&prev_graph));
144145let colors = DepNodeColorMap::new(prev_graph_node_count);
146147// Instantiate a node with zero dependencies only once for anonymous queries.
148let _green_node_index = current.alloc_new_node(
149DepNode { kind: DepKind::AnonZeroDeps, key_fingerprint: current.anon_id_seed.into() },
150EdgesVec::new(),
151Fingerprint::ZERO,
152 );
153match (&_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);
154155// Create a single always-red node, with no dependencies of its own.
156 // Other nodes can use the always-red node as a fake dependency, to
157 // ensure that their dependency list will never be all-green.
158let red_node_index = current.alloc_new_node(
159DepNode { kind: DepKind::Red, key_fingerprint: Fingerprint::ZERO.into() },
160EdgesVec::new(),
161Fingerprint::ZERO,
162 );
163match (&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);
164if prev_graph_node_count > 0 {
165let prev_index =
166const { SerializedDepNodeIndex::from_u32(DepNodeIndex::FOREVER_RED_NODE.as_u32()) };
167let result = colors.try_set_color(prev_index, DesiredColor::Red);
168{
match result {
TrySetColorResult::Success => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TrySetColorResult::Success", ::core::option::Option::None);
}
}
};assert_matches!(result, TrySetColorResult::Success);
169 }
170171DepGraph {
172 data: Some(Arc::new(DepGraphData {
173 previous_work_products: prev_work_products,
174current,
175 previous: prev_graph,
176colors,
177 debug_loaded_from_disk: Default::default(),
178 })),
179 virtual_dep_node_index: Arc::new(AtomicU32::new(0)),
180 }
181 }
182183pub fn new_disabled() -> DepGraph {
184DepGraph { data: None, virtual_dep_node_index: Arc::new(AtomicU32::new(0)) }
185 }
186187#[inline]
188pub fn data(&self) -> Option<&DepGraphData> {
189self.data.as_deref()
190 }
191192/// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
193#[inline]
194pub fn is_fully_enabled(&self) -> bool {
195self.data.is_some()
196 }
197198pub fn with_retained_dep_graph(&self, f: impl Fn(&RetainedDepGraph)) {
199if let Some(data) = &self.data {
200data.current.encoder.with_retained_dep_graph(f)
201 }
202 }
203204pub fn assert_ignored(&self) {
205if let Some(..) = self.data {
206read_deps(|task_deps| {
207{
match task_deps {
TaskDepsRef::Ignore => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"TaskDepsRef::Ignore",
::core::option::Option::Some(format_args!("expected no task dependency tracking")));
}
}
};assert_matches!(
208 task_deps,
209 TaskDepsRef::Ignore,
210"expected no task dependency tracking"
211);
212 })
213 }
214 }
215216pub fn with_ignore<OP, R>(&self, op: OP) -> R
217where
218OP: FnOnce() -> R,
219 {
220with_deps(TaskDepsRef::Ignore, op)
221 }
222223/// Used to wrap the deserialization of a query result from disk,
224 /// This method enforces that no new `DepNodes` are created during
225 /// query result deserialization.
226 ///
227 /// Enforcing this makes the query dep graph simpler - all nodes
228 /// must be created during the query execution, and should be
229 /// created from inside the 'body' of a query (the implementation
230 /// provided by a particular compiler crate).
231 ///
232 /// Consider the case of three queries `A`, `B`, and `C`, where
233 /// `A` invokes `B` and `B` invokes `C`:
234 ///
235 /// `A -> B -> C`
236 ///
237 /// Suppose that decoding the result of query `B` required re-computing
238 /// the query `C`. If we did not create a fresh `TaskDeps` when
239 /// decoding `B`, we would still be using the `TaskDeps` for query `A`
240 /// (if we needed to re-execute `A`). This would cause us to create
241 /// a new edge `A -> C`. If this edge did not previously
242 /// exist in the `DepGraph`, then we could end up with a different
243 /// `DepGraph` at the end of compilation, even if there were no
244 /// meaningful changes to the overall program (e.g. a newline was added).
245 /// In addition, this edge might cause a subsequent compilation run
246 /// to try to force `C` before marking other necessary nodes green. If
247 /// `C` did not exist in the new compilation session, then we could
248 /// get an ICE. Normally, we would have tried (and failed) to mark
249 /// some other query green (e.g. `item_children`) which was used
250 /// to obtain `C`, which would prevent us from ever trying to force
251 /// a nonexistent `D`.
252 ///
253 /// It might be possible to enforce that all `DepNode`s read during
254 /// deserialization already exist in the previous `DepGraph`. In
255 /// the above example, we would invoke `D` during the deserialization
256 /// of `B`. Since we correctly create a new `TaskDeps` from the decoding
257 /// of `B`, this would result in an edge `B -> D`. If that edge already
258 /// existed (with the same `DepPathHash`es), then it should be correct
259 /// to allow the invocation of the query to proceed during deserialization
260 /// of a query result. We would merely assert that the dep-graph fragment
261 /// that would have been added by invoking `C` while decoding `B`
262 /// is equivalent to the dep-graph fragment that we already instantiated for B
263 /// (at the point where we successfully marked B as green).
264 ///
265 /// However, this would require additional complexity
266 /// in the query infrastructure, and is not currently needed by the
267 /// decoding of any query results. Should the need arise in the future,
268 /// we should consider extending the query system with this functionality.
269pub fn with_query_deserialization<OP, R>(&self, op: OP) -> R
270where
271OP: FnOnce() -> R,
272 {
273with_deps(TaskDepsRef::Forbid, op)
274 }
275276#[inline(always)]
277pub fn with_task<'tcx, OP, R>(
278&self,
279 dep_node: DepNode,
280 tcx: TyCtxt<'tcx>,
281 op: OP,
282 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
283 ) -> (R, DepNodeIndex)
284where
285OP: FnOnce() -> R,
286 {
287match self.data() {
288Some(data) => data.with_task(dep_node, tcx, op, hash_result),
289None => (op(), self.next_virtual_depnode_index()),
290 }
291 }
292293pub fn with_anon_task<'tcx, OP, R>(
294&self,
295 tcx: TyCtxt<'tcx>,
296 dep_kind: DepKind,
297 op: OP,
298 ) -> (R, DepNodeIndex)
299where
300OP: FnOnce() -> R,
301 {
302match self.data() {
303Some(data) => {
304let (result, index) = data.with_anon_task_inner(tcx, dep_kind, op);
305self.read_index(index);
306 (result, index)
307 }
308None => (op(), self.next_virtual_depnode_index()),
309 }
310 }
311}
312313impl DepGraphData {
314#[inline(always)]
315pub fn with_task<'tcx, OP, R>(
316&self,
317 dep_node: DepNode,
318 tcx: TyCtxt<'tcx>,
319 op: OP,
320 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
321 ) -> (R, DepNodeIndex)
322where
323OP: FnOnce() -> R,
324 {
325// If the following assertion triggers, it can have two reasons:
326 // 1. Something is wrong with DepNode creation, either here or
327 // in `DepGraph::try_mark_green()`.
328 // 2. Two distinct query keys get mapped to the same `DepNode`
329 // (see for example #48923).
330self.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
331::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:?}")332 });
333334let (result, edges) = if tcx.is_eval_always(dep_node.kind) {
335 (with_deps(TaskDepsRef::EvalAlways, op), EdgesVec::new())
336 } else {
337let task_deps = Lock::new(TaskDeps::new(
338#[cfg(debug_assertions)]
339Some(dep_node),
3400,
341 ));
342 (with_deps(TaskDepsRef::Allow(&task_deps), op), task_deps.into_inner().reads)
343 };
344345let dep_node_index =
346self.hash_result_and_alloc_node(tcx, dep_node, edges, &result, hash_result);
347348 (result, dep_node_index)
349 }
350351/// Executes something within an "anonymous" task, that is, a task the
352 /// `DepNode` of which is determined by the list of inputs it read from.
353 ///
354 /// NOTE: this does not actually count as a read of the DepNode here.
355 /// Using the result of this task without reading the DepNode will result
356 /// in untracked dependencies which may lead to ICEs as nodes are
357 /// incorrectly marked green.
358 ///
359 /// FIXME: This could perhaps return a `WithDepNode` to ensure that the
360 /// user of this function actually performs the read.
361fn with_anon_task_inner<'tcx, OP, R>(
362&self,
363 tcx: TyCtxt<'tcx>,
364 dep_kind: DepKind,
365 op: OP,
366 ) -> (R, DepNodeIndex)
367where
368OP: FnOnce() -> R,
369 {
370if 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));
371372// Large numbers of reads are common enough here that pre-sizing `read_set`
373 // to 128 actually helps perf on some benchmarks.
374let task_deps = Lock::new(TaskDeps::new(
375#[cfg(debug_assertions)]
376None,
377128,
378 ));
379let result = with_deps(TaskDepsRef::Allow(&task_deps), op);
380let task_deps = task_deps.into_inner();
381let reads = task_deps.reads;
382383let dep_node_index = match reads.len() {
3840 => {
385// Because the dep-node id of anon nodes is computed from the sets of its
386 // dependencies we already know what the ID of this dependency-less node is
387 // going to be (i.e. equal to the precomputed
388 // `SINGLETON_DEPENDENCYLESS_ANON_NODE`). As a consequence we can skip creating
389 // a `StableHasher` and sending the node through interning.
390DepNodeIndex::SINGLETON_ZERO_DEPS_ANON_NODE391 }
3921 => {
393// When there is only one dependency, don't bother creating a node.
394reads[0]
395 }
396_ => {
397// The dep node indices are hashed here instead of hashing the dep nodes of the
398 // dependencies. These indices may refer to different nodes per session, but this
399 // isn't a problem here because we that ensure the final dep node hash is per
400 // session only by combining it with the per session `anon_id_seed`. This hash only
401 // need to map the dependencies to a single value on a per session basis.
402let mut hasher = StableHasher::new();
403reads.hash(&mut hasher);
404405let target_dep_node = DepNode {
406 kind: dep_kind,
407// Fingerprint::combine() is faster than sending Fingerprint
408 // through the StableHasher (at least as long as StableHasher
409 // is so slow).
410key_fingerprint: self.current.anon_id_seed.combine(hasher.finish()).into(),
411 };
412413// The DepNodes generated by the process above are not unique. 2 queries could
414 // have exactly the same dependencies. However, deserialization does not handle
415 // duplicated nodes, so we do the deduplication here directly.
416 //
417 // As anonymous nodes are a small quantity compared to the full dep-graph, the
418 // memory impact of this `anon_node_to_index` map remains tolerable, and helps
419 // us avoid useless growth of the graph with almost-equivalent nodes.
420self.current.anon_node_to_index.get_or_insert_with(target_dep_node, || {
421self.current.alloc_new_node(target_dep_node, reads, Fingerprint::ZERO)
422 })
423 }
424 };
425426 (result, dep_node_index)
427 }
428429/// Intern the new `DepNode` with the dependencies up-to-now.
430fn hash_result_and_alloc_node<'tcx, R>(
431&self,
432 tcx: TyCtxt<'tcx>,
433 node: DepNode,
434 edges: EdgesVec,
435 result: &R,
436 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
437 ) -> DepNodeIndex {
438let hashing_timer = tcx.prof.incr_result_hashing();
439let current_fingerprint = hash_result.map(|hash_result| {
440tcx.with_stable_hashing_context(|mut hcx| hash_result(&mut hcx, result))
441 });
442let dep_node_index = self.alloc_and_color_node(node, edges, current_fingerprint);
443hashing_timer.finish_with_query_invocation_id(dep_node_index.into());
444dep_node_index445 }
446}
447448impl DepGraph {
449#[inline]
450pub fn read_index(&self, dep_node_index: DepNodeIndex) {
451if let Some(ref data) = self.data {
452read_deps(|task_deps| {
453let mut task_deps = match task_deps {
454 TaskDepsRef::Allow(deps) => deps.lock(),
455 TaskDepsRef::EvalAlways => {
456// We don't need to record dependencies of eval_always
457 // queries. They are re-evaluated unconditionally anyway.
458return;
459 }
460 TaskDepsRef::Ignore => return,
461 TaskDepsRef::Forbid => {
462// Reading is forbidden in this context. ICE with a useful error message.
463panic_on_forbidden_read(data, dep_node_index)
464 }
465 };
466let task_deps = &mut *task_deps;
467468if truecfg!(debug_assertions) {
469data.current.total_read_count.fetch_add(1, Ordering::Relaxed);
470 }
471472// Has `dep_node_index` been seen before? Use either a linear scan or a hashset
473 // lookup to determine this. See `TaskDeps::read_set` for details.
474let new_read = if task_deps.reads.len() <= TaskDeps::LINEAR_SCAN_MAX {
475 !task_deps.reads.contains(&dep_node_index)
476 } else {
477task_deps.read_set.insert(dep_node_index)
478 };
479if new_read {
480task_deps.reads.push(dep_node_index);
481if task_deps.reads.len() == TaskDeps::LINEAR_SCAN_MAX + 1 {
482// Fill `read_set` with what we have so far. Future lookups will use it.
483task_deps.read_set.extend(task_deps.reads.iter().copied());
484 }
485486#[cfg(debug_assertions)]
487{
488if let Some(target) = task_deps.node
489 && let Some(ref forbidden_edge) = data.current.forbidden_edge
490 {
491let src = forbidden_edge.index_to_node.lock()[&dep_node_index];
492if forbidden_edge.test(&src, &target) {
493{
::core::panicking::panic_fmt(format_args!("forbidden edge {0:?} -> {1:?} created",
src, target));
}panic!("forbidden edge {:?} -> {:?} created", src, target)494 }
495 }
496 }
497 } else if truecfg!(debug_assertions) {
498data.current.total_duplicate_read_count.fetch_add(1, Ordering::Relaxed);
499 }
500 })
501 }
502 }
503504/// This encodes a side effect by creating a node with an unique index and associating
505 /// it with the node, for use in the next session.
506#[inline]
507pub fn record_diagnostic<'tcx>(&self, tcx: TyCtxt<'tcx>, diagnostic: &DiagInner) {
508if let Some(ref data) = self.data {
509read_deps(|task_deps| match task_deps {
510 TaskDepsRef::EvalAlways | TaskDepsRef::Ignore => return,
511 TaskDepsRef::Forbid | TaskDepsRef::Allow(..) => {
512let dep_node_index = data513 .encode_side_effect(tcx, QuerySideEffect::Diagnostic(diagnostic.clone()));
514self.read_index(dep_node_index);
515 }
516 })
517 }
518 }
519/// This forces a side effect node green by running its side effect. `prev_index` would
520 /// refer to a node created used `encode_side_effect` in the previous session.
521#[inline]
522pub fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
523if let Some(ref data) = self.data {
524data.force_side_effect(tcx, prev_index);
525 }
526 }
527528#[inline]
529pub fn encode_side_effect<'tcx>(
530&self,
531 tcx: TyCtxt<'tcx>,
532 side_effect: QuerySideEffect,
533 ) -> DepNodeIndex {
534if let Some(ref data) = self.data {
535data.encode_side_effect(tcx, side_effect)
536 } else {
537self.next_virtual_depnode_index()
538 }
539 }
540541/// Create a node when we force-feed a value into the query cache.
542 /// This is used to remove cycles during type-checking const generic parameters.
543 ///
544 /// As usual in the query system, we consider the current state of the calling query
545 /// only depends on the list of dependencies up to now. As a consequence, the value
546 /// that this query gives us can only depend on those dependencies too. Therefore,
547 /// it is sound to use the current dependency set for the created node.
548 ///
549 /// During replay, the order of the nodes is relevant in the dependency graph.
550 /// So the unchanged replay will mark the caller query before trying to mark this one.
551 /// If there is a change to report, the caller query will be re-executed before this one.
552 ///
553 /// FIXME: If the code is changed enough for this node to be marked before requiring the
554 /// caller's node, we suppose that those changes will be enough to mark this node red and
555 /// force a recomputation using the "normal" way.
556pub fn with_feed_task<'tcx, R>(
557&self,
558 node: DepNode,
559 tcx: TyCtxt<'tcx>,
560 result: &R,
561 hash_result: Option<fn(&mut StableHashState<'_>, &R) -> Fingerprint>,
562 format_value_fn: fn(&R) -> String,
563 ) -> DepNodeIndex {
564if let Some(data) = self.data.as_ref() {
565// The caller query has more dependencies than the node we are creating. We may
566 // encounter a case where this created node is marked as green, but the caller query is
567 // subsequently marked as red or recomputed. In this case, we will end up feeding a
568 // value to an existing node.
569 //
570 // For sanity, we still check that the loaded stable hash and the new one match.
571if let Some(prev_index) = data.previous.node_to_index_opt(&node) {
572let dep_node_index = data.colors.current(prev_index);
573if let Some(dep_node_index) = dep_node_index {
574incremental_verify_ich(
575tcx,
576data,
577result,
578prev_index,
579hash_result,
580format_value_fn,
581 );
582583#[cfg(debug_assertions)]
584if hash_result.is_some() {
585data.current.record_edge(
586dep_node_index,
587node,
588data.prev_value_fingerprint_of(prev_index),
589 );
590 }
591592return dep_node_index;
593 }
594 }
595596let mut edges = EdgesVec::new();
597read_deps(|task_deps| match task_deps {
598 TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()),
599 TaskDepsRef::EvalAlways => {
600edges.push(DepNodeIndex::FOREVER_RED_NODE);
601 }
602 TaskDepsRef::Ignore => {}
603 TaskDepsRef::Forbid => {
604{
::core::panicking::panic_fmt(format_args!("Cannot summarize when dependencies are not recorded."));
}panic!("Cannot summarize when dependencies are not recorded.")605 }
606 });
607608data.hash_result_and_alloc_node(tcx, node, edges, result, hash_result)
609 } else {
610// Incremental compilation is turned off. We just execute the task
611 // without tracking. We still provide a dep-node index that uniquely
612 // identifies the task so that we have a cheap way of referring to
613 // the query for self-profiling.
614self.next_virtual_depnode_index()
615 }
616 }
617}
618619impl DepGraphData {
620fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
621&self,
622 sess: &Session,
623 dep_node: &DepNode,
624 msg: impl FnOnce() -> S,
625 ) {
626if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
627let color = self.colors.get(prev_index);
628let ok = match color {
629 DepNodeColor::Unknown => true,
630 DepNodeColor::Red => false,
631 DepNodeColor::Green(..) => sess.threads().is_some(), // Other threads may mark this green
632};
633if !ok {
634{ ::core::panicking::panic_display(&msg()); }panic!("{}", msg())635 }
636 }
637 }
638639fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
640if let Some(prev_index) = self.previous.node_to_index_opt(dep_node) {
641self.colors.get(prev_index)
642 } else {
643// This is a node that did not exist in the previous compilation session.
644DepNodeColor::Unknown645 }
646 }
647648/// Returns true if the given node has been marked as green during the
649 /// current compilation session. Used in various assertions
650#[inline]
651pub fn is_index_green(&self, prev_index: SerializedDepNodeIndex) -> bool {
652#[allow(non_exhaustive_omitted_patterns)] match self.colors.get(prev_index) {
DepNodeColor::Green(_) => true,
_ => false,
}matches!(self.colors.get(prev_index), DepNodeColor::Green(_))653 }
654655#[inline]
656pub fn prev_value_fingerprint_of(&self, prev_index: SerializedDepNodeIndex) -> Fingerprint {
657self.previous.value_fingerprint_for_index(prev_index)
658 }
659660#[inline]
661pub(crate) fn prev_node_of(&self, prev_index: SerializedDepNodeIndex) -> &DepNode {
662self.previous.index_to_node(prev_index)
663 }
664665pub fn mark_debug_loaded_from_disk(&self, dep_node: DepNode) {
666self.debug_loaded_from_disk.lock().insert(dep_node);
667 }
668669/// This encodes a side effect by creating a node with an unique index and associating
670 /// it with the node, for use in the next session.
671#[inline]
672fn encode_side_effect<'tcx>(
673&self,
674 tcx: TyCtxt<'tcx>,
675 side_effect: QuerySideEffect,
676 ) -> DepNodeIndex {
677// Use `send_new` so we get an unique index, even though the dep node is not.
678let dep_node_index = self.current.encoder.send_new(
679DepNode {
680 kind: DepKind::SideEffect,
681 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
682 },
683Fingerprint::ZERO,
684// We want the side effect node to always be red so it will be forced and run the
685 // side effect.
686std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
687 );
688tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
689dep_node_index690 }
691692/// This forces a side effect node green by running its side effect. `prev_index` would
693 /// refer to a node created used `encode_side_effect` in the previous session.
694#[inline]
695fn force_side_effect<'tcx>(&self, tcx: TyCtxt<'tcx>, prev_index: SerializedDepNodeIndex) {
696with_deps(TaskDepsRef::Ignore, || {
697let side_effect = tcx698 .query_system
699 .on_disk_cache
700 .as_ref()
701 .unwrap()
702 .load_side_effect(tcx, prev_index)
703 .unwrap();
704705// Use `send_and_color` as `promote_node_and_deps_to_current` expects all
706 // green dependencies. `send_and_color` will also prevent multiple nodes
707 // being encoded for concurrent calls.
708let dep_node_index = self.current.encoder.send_and_color(
709prev_index,
710&self.colors,
711DepNode {
712 kind: DepKind::SideEffect,
713 key_fingerprint: PackedFingerprint::from(Fingerprint::ZERO),
714 },
715Fingerprint::ZERO,
716 std::iter::once(DepNodeIndex::FOREVER_RED_NODE).collect(),
717true,
718 );
719720match &side_effect {
721 QuerySideEffect::Diagnostic(diagnostic) => {
722tcx.dcx().emit_diagnostic(diagnostic.clone());
723 }
724 QuerySideEffect::CheckFeature { symbol } => {
725tcx.sess.used_features.lock().insert(*symbol, dep_node_index.as_u32());
726 }
727 }
728729// This will just overwrite the same value for concurrent calls.
730tcx.query_system.side_effects.borrow_mut().insert(dep_node_index, side_effect);
731 })
732 }
733734fn alloc_and_color_node(
735&self,
736 key: DepNode,
737 edges: EdgesVec,
738 value_fingerprint: Option<Fingerprint>,
739 ) -> DepNodeIndex {
740if let Some(prev_index) = self.previous.node_to_index_opt(&key) {
741// Determine the color and index of the new `DepNode`.
742let is_green = if let Some(value_fingerprint) = value_fingerprint {
743if value_fingerprint == self.previous.value_fingerprint_for_index(prev_index) {
744// This is a green node: it existed in the previous compilation,
745 // its query was re-executed, and it has the same result as before.
746true
747} else {
748// This is a red node: it existed in the previous compilation, its query
749 // was re-executed, but it has a different result from before.
750false
751}
752 } else {
753// This is a red node, effectively: it existed in the previous compilation
754 // session, its query was re-executed, but it doesn't compute a result hash
755 // (i.e. it represents a `no_hash` query), so we have no way of determining
756 // whether or not the result was the same as before.
757false
758};
759760let value_fingerprint = value_fingerprint.unwrap_or(Fingerprint::ZERO);
761762let dep_node_index = self.current.encoder.send_and_color(
763prev_index,
764&self.colors,
765key,
766value_fingerprint,
767edges,
768is_green,
769 );
770771#[cfg(debug_assertions)]
772self.current.record_edge(dep_node_index, key, value_fingerprint);
773774dep_node_index775 } else {
776self.current.alloc_new_node(key, edges, value_fingerprint.unwrap_or(Fingerprint::ZERO))
777 }
778 }
779780fn promote_node_and_deps_to_current(
781&self,
782 prev_index: SerializedDepNodeIndex,
783 ) -> Option<DepNodeIndex> {
784let dep_node_index = self.current.encoder.send_promoted(prev_index, &self.colors);
785786#[cfg(debug_assertions)]
787if let Some(dep_node_index) = dep_node_index {
788self.current.record_edge(
789dep_node_index,
790*self.previous.index_to_node(prev_index),
791self.previous.value_fingerprint_for_index(prev_index),
792 );
793 }
794795dep_node_index796 }
797}
798799impl DepGraph {
800/// Checks whether a previous work product exists for `v` and, if
801 /// so, return the path that leads to it. Used to skip doing work.
802pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
803self.data.as_ref().and_then(|data| data.previous_work_products.get(v).cloned())
804 }
805806/// Access the map of work-products created during the cached run. Only
807 /// used during saving of the dep-graph.
808pub fn previous_work_products(&self) -> &WorkProductMap {
809&self.data.as_ref().unwrap().previous_work_products
810 }
811812pub fn debug_was_loaded_from_disk(&self, dep_node: DepNode) -> bool {
813self.data.as_ref().unwrap().debug_loaded_from_disk.lock().contains(&dep_node)
814 }
815816pub fn debug_dep_kind_was_loaded_from_disk(&self, dep_kind: DepKind) -> bool {
817// We only check if we have a dep node corresponding to the given dep kind.
818#[allow(rustc::potential_query_instability)]
819self.data
820 .as_ref()
821 .unwrap()
822 .debug_loaded_from_disk
823 .lock()
824 .iter()
825 .any(|node| node.kind == dep_kind)
826 }
827828fn node_color(&self, dep_node: &DepNode) -> DepNodeColor {
829if let Some(ref data) = self.data {
830return data.node_color(dep_node);
831 }
832833 DepNodeColor::Unknown834 }
835836pub fn try_mark_green<'tcx>(
837&self,
838 tcx: TyCtxt<'tcx>,
839 dep_node: &DepNode,
840 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
841self.data()?.try_mark_green(tcx, dep_node)
842 }
843}
844845impl DepGraphData {
846/// Try to mark a node index for the node dep_node.
847 ///
848 /// A node will have an index, when it's already been marked green, or when we can mark it
849 /// green. This function will mark the current task as a reader of the specified node, when
850 /// a node index can be found for that node.
851pub fn try_mark_green<'tcx>(
852&self,
853 tcx: TyCtxt<'tcx>,
854 dep_node: &DepNode,
855 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
856if 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));
857858// Return None if the dep node didn't exist in the previous session
859let prev_index = self.previous.node_to_index_opt(dep_node)?;
860861if 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);
862863match self.colors.get(prev_index) {
864 DepNodeColor::Green(dep_node_index) => Some((prev_index, dep_node_index)),
865 DepNodeColor::Red => None,
866 DepNodeColor::Unknown => {
867// This DepNode and the corresponding query invocation existed
868 // in the previous compilation session too, so we can try to
869 // mark it as green by recursively marking all of its
870 // dependencies green.
871self.try_mark_previous_green(tcx, prev_index, None)
872 .map(|dep_node_index| (prev_index, dep_node_index))
873 }
874 }
875 }
876877/// Try to mark a dep-node which existed in the previous compilation session as green.
878#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_mark_previous_green",
"rustc_middle::dep_graph::graph", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/dep_graph/graph.rs"),
::tracing_core::__macro_support::Option::Some(878u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::dep_graph::graph"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Option<DepNodeIndex> = loop {};
return __tracing_attr_fake_return;
}
{
let frame =
MarkFrame { index: prev_dep_node_index, parent: frame };
if true {
if !!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)
{
::core::panicking::panic("assertion failed: !tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind)")
};
};
for parent_dep_node_index in
self.previous.edge_targets_from(prev_dep_node_index) {
match self.colors.get(parent_dep_node_index) {
DepNodeColor::Green(_) => continue,
DepNodeColor::Red => return None,
DepNodeColor::Unknown => {}
}
let parent_dep_node =
self.previous.index_to_node(parent_dep_node_index);
if !tcx.is_eval_always(parent_dep_node.kind) &&
self.try_mark_previous_green(tcx, parent_dep_node_index,
Some(&frame)).is_some() {
continue;
}
if !tcx.try_force_from_dep_node(*parent_dep_node,
parent_dep_node_index, &frame) {
return None;
}
match self.colors.get(parent_dep_node_index) {
DepNodeColor::Green(_) => continue,
DepNodeColor::Red => return None,
DepNodeColor::Unknown => {}
}
if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
{
::core::panicking::panic_fmt(format_args!("try_mark_previous_green() - forcing failed to set a color"));
};
}
return None;
}
let dep_node_index =
self.promote_node_and_deps_to_current(prev_dep_node_index)?;
Some(dep_node_index)
}
}
}#[instrument(skip(self, tcx, prev_dep_node_index, frame), level = "debug")]879fn try_mark_previous_green<'tcx>(
880&self,
881 tcx: TyCtxt<'tcx>,
882 prev_dep_node_index: SerializedDepNodeIndex,
883 frame: Option<&MarkFrame<'_>>,
884 ) -> Option<DepNodeIndex> {
885let frame = MarkFrame { index: prev_dep_node_index, parent: frame };
886887// We never try to mark eval_always nodes as green
888debug_assert!(!tcx.is_eval_always(self.previous.index_to_node(prev_dep_node_index).kind));
889890for parent_dep_node_index in self.previous.edge_targets_from(prev_dep_node_index) {
891match self.colors.get(parent_dep_node_index) {
892// This dependency has been marked as green before, we are still ok and can
893 // continue checking the remaining dependencies.
894DepNodeColor::Green(_) => continue,
895896// This dependency's result is different to the previous compilation session. We
897 // cannot mark this dep_node as green, so stop checking.
898DepNodeColor::Red => return None,
899900// We still need to determine this dependency's colour.
901DepNodeColor::Unknown => {}
902 }
903904let parent_dep_node = self.previous.index_to_node(parent_dep_node_index);
905906// If this dependency isn't eval_always, try to mark it green recursively.
907if !tcx.is_eval_always(parent_dep_node.kind)
908 && self.try_mark_previous_green(tcx, parent_dep_node_index, Some(&frame)).is_some()
909 {
910continue;
911 }
912913// We failed to mark it green, so we try to force the query.
914if !tcx.try_force_from_dep_node(*parent_dep_node, parent_dep_node_index, &frame) {
915return None;
916 }
917918match self.colors.get(parent_dep_node_index) {
919 DepNodeColor::Green(_) => continue,
920 DepNodeColor::Red => return None,
921 DepNodeColor::Unknown => {}
922 }
923924if tcx.dcx().has_errors_or_delayed_bugs().is_none() {
925panic!("try_mark_previous_green() - forcing failed to set a color");
926 }
927928// If the query we just forced has resulted in some kind of compilation error, we
929 // cannot rely on the dep-node color having been properly updated. This means that the
930 // query system has reached an invalid state. We let the compiler continue (by
931 // returning `None`) so it can emit error messages and wind down, but rely on the fact
932 // that this invalid state will not be persisted to the incremental compilation cache
933 // because of compilation errors being present.
934return None;
935 }
936937// If we got here without hitting a `return` that means that all
938 // dependencies of this DepNode could be marked as green. Therefore we
939 // can also mark this DepNode as green.
940941 // There may be multiple threads trying to mark the same dep node green concurrently.
942943 // We allocating an entry for the node in the current dependency graph and
944 // adding all the appropriate edges imported from the previous graph.
945 //
946 // `no_hash` nodes may fail this promotion due to already being conservatively colored red.
947let dep_node_index = self.promote_node_and_deps_to_current(prev_dep_node_index)?;
948949// ... and finally storing a "Green" entry in the color map.
950 // Multiple threads can all write the same color here.
951952Some(dep_node_index)
953 }
954}
955956impl DepGraph {
957/// Returns true if the given node has been marked as red during the
958 /// current compilation session. Used in various assertions
959pub fn is_red(&self, dep_node: &DepNode) -> bool {
960#[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
DepNodeColor::Red => true,
_ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Red)961 }
962963/// Returns true if the given node has been marked as green during the
964 /// current compilation session. Used in various assertions
965pub fn is_green(&self, dep_node: &DepNode) -> bool {
966#[allow(non_exhaustive_omitted_patterns)] match self.node_color(dep_node) {
DepNodeColor::Green(_) => true,
_ => false,
}matches!(self.node_color(dep_node), DepNodeColor::Green(_))967 }
968969pub fn assert_dep_node_not_yet_allocated_in_current_session<S: std::fmt::Display>(
970&self,
971 sess: &Session,
972 dep_node: &DepNode,
973 msg: impl FnOnce() -> S,
974 ) {
975if let Some(data) = &self.data {
976data.assert_dep_node_not_yet_allocated_in_current_session(sess, dep_node, msg)
977 }
978 }
979980/// This method loads all on-disk cacheable query results into memory, so
981 /// they can be written out to the new cache file again. Most query results
982 /// will already be in memory but in the case where we marked something as
983 /// green but then did not need the value, that value will never have been
984 /// loaded from disk.
985 ///
986 /// This method will only load queries that will end up in the disk cache.
987 /// Other queries will not be executed.
988pub fn exec_cache_promotions<'tcx>(&self, tcx: TyCtxt<'tcx>) {
989let _prof_timer = tcx.prof.generic_activity("incr_comp_query_cache_promotion");
990991let data = self.data.as_ref().unwrap();
992for prev_index in data.colors.values.indices() {
993match data.colors.get(prev_index) {
994 DepNodeColor::Green(_) => {
995let dep_node = data.previous.index_to_node(prev_index);
996if let Some(promote_fn) =
997 tcx.dep_kind_vtable(dep_node.kind).promote_from_disk_fn
998 {
999 promote_fn(tcx, *dep_node)
1000 };
1001 }
1002 DepNodeColor::Unknown | DepNodeColor::Red => {
1003// We can skip red nodes because a node can only be marked
1004 // as red if the query result was recomputed and thus is
1005 // already in memory.
1006}
1007 }
1008 }
1009 }
10101011pub(crate) fn finish_encoding(&self) -> FileEncodeResult {
1012if let Some(data) = &self.data { data.current.encoder.finish(&data.current) } else { Ok(0) }
1013 }
10141015pub fn next_virtual_depnode_index(&self) -> DepNodeIndex {
1016if true {
if !self.data.is_none() {
::core::panicking::panic("assertion failed: self.data.is_none()")
};
};debug_assert!(self.data.is_none());
1017let index = self.virtual_dep_node_index.fetch_add(1, Ordering::Relaxed);
1018DepNodeIndex::from_u32(index)
1019 }
1020}
10211022/// A "work product" is an intermediate result that we save into the
1023/// incremental directory for later re-use. The primary example are
1024/// the object files that we save for each partition at code
1025/// generation time.
1026///
1027/// Each work product is associated with a dep-node, representing the
1028/// process that produced the work-product. If that dep-node is found
1029/// to be dirty when we load up, then we will delete the work-product
1030/// at load time. If the work-product is found to be clean, then we
1031/// will keep a record in the `previous_work_products` list.
1032///
1033/// In addition, work products have an associated hash. This hash is
1034/// an extra hash that can be used to decide if the work-product from
1035/// a previous compilation can be re-used (in addition to the dirty
1036/// edges check).
1037///
1038/// As the primary example, consider the object files we generate for
1039/// each partition. In the first run, we create partitions based on
1040/// the symbols that need to be compiled. For each partition P, we
1041/// hash the symbols in P and create a `WorkProduct` record associated
1042/// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
1043/// in P.
1044///
1045/// The next time we compile, if the `DepNode::CodegenUnit(P)` is
1046/// judged to be clean (which means none of the things we read to
1047/// generate the partition were found to be dirty), it will be loaded
1048/// into previous work products. We will then regenerate the set of
1049/// symbols in the partition P and hash them (note that new symbols
1050/// may be added -- for example, new monomorphizations -- even if
1051/// nothing in P changed!). We will compare that hash against the
1052/// previous hash. If it matches up, we can reuse the object file.
1053#[derive(#[automatically_derived]
impl ::core::clone::Clone for WorkProduct {
#[inline]
fn clone(&self) -> WorkProduct {
WorkProduct {
cgu_name: ::core::clone::Clone::clone(&self.cgu_name),
saved_files: ::core::clone::Clone::clone(&self.saved_files),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for WorkProduct {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "WorkProduct",
"cgu_name", &self.cgu_name, "saved_files", &&self.saved_files)
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for WorkProduct {
fn encode(&self, __encoder: &mut __E) {
match *self {
WorkProduct {
cgu_name: ref __binding_0, saved_files: ref __binding_1 } =>
{
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for WorkProduct {
fn decode(__decoder: &mut __D) -> Self {
WorkProduct {
cgu_name: ::rustc_serialize::Decodable::decode(__decoder),
saved_files: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
1054pub struct WorkProduct {
1055pub cgu_name: String,
1056/// Saved files associated with this CGU. In each key/value pair, the value is the path to the
1057 /// saved file and the key is some identifier for the type of file being saved.
1058 ///
1059 /// By convention, file extensions are currently used as identifiers, i.e. the key "o" maps to
1060 /// the object file's path, and "dwo" to the dwarf object file's path.
1061pub saved_files: UnordMap<String, String>,
1062}
10631064pub type WorkProductMap = UnordMap<WorkProductId, WorkProduct>;
10651066// Index type for `DepNodeData`'s edges.
1067impl ::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! {
1068struct EdgeIndex {}
1069}10701071/// `CurrentDepGraph` stores the dependency graph for the current session. It
1072/// will be populated as we run queries or tasks. We never remove nodes from the
1073/// graph: they are only added.
1074///
1075/// The nodes in it are identified by a `DepNodeIndex`. We avoid keeping the nodes
1076/// in memory. This is important, because these graph structures are some of the
1077/// largest in the compiler.
1078///
1079/// For this reason, we avoid storing `DepNode`s more than once as map
1080/// keys. The `anon_node_to_index` map only contains nodes of anonymous queries not in the previous
1081/// graph, and we map nodes in the previous graph to indices via a two-step
1082/// mapping. `SerializedDepGraph` maps from `DepNode` to `SerializedDepNodeIndex`,
1083/// and the `prev_index_to_index` vector (which is more compact and faster than
1084/// using a map) maps from `SerializedDepNodeIndex` to `DepNodeIndex`.
1085///
1086/// This struct uses three locks internally. The `data`, `anon_node_to_index`,
1087/// and `prev_index_to_index` fields are locked separately. Operations that take
1088/// a `DepNodeIndex` typically just access the `data` field.
1089///
1090/// We only need to manipulate at most two locks simultaneously:
1091/// `anon_node_to_index` and `data`, or `prev_index_to_index` and `data`. When
1092/// manipulating both, we acquire `anon_node_to_index` or `prev_index_to_index`
1093/// first, and `data` second.
1094pub(super) struct CurrentDepGraph {
1095 encoder: GraphEncoder,
1096 anon_node_to_index: ShardedHashMap<DepNode, DepNodeIndex>,
10971098/// This is used to verify that value fingerprints do not change between the
1099 /// creation of a node and its recomputation.
1100#[cfg(debug_assertions)]
1101value_fingerprints: Lock<IndexVec<DepNodeIndex, Option<Fingerprint>>>,
11021103/// Used to trap when a specific edge is added to the graph.
1104 /// This is used for debug purposes and is only active with `debug_assertions`.
1105#[cfg(debug_assertions)]
1106forbidden_edge: Option<EdgeFilter>,
11071108/// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
1109 /// their edges. This has the beneficial side-effect that multiple anonymous
1110 /// nodes can be coalesced into one without changing the semantics of the
1111 /// dependency graph. However, the merging of nodes can lead to a subtle
1112 /// problem during red-green marking: The color of an anonymous node from
1113 /// the current session might "shadow" the color of the node with the same
1114 /// ID from the previous session. In order to side-step this problem, we make
1115 /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
1116 /// This is implemented by mixing a session-key into the ID fingerprint of
1117 /// each anon node. The session-key is a hash of the number of previous sessions.
1118anon_id_seed: Fingerprint,
11191120/// These are simple counters that are for profiling and
1121 /// debugging and only active with `debug_assertions`.
1122pub(super) total_read_count: AtomicU64,
1123pub(super) total_duplicate_read_count: AtomicU64,
1124}
11251126impl CurrentDepGraph {
1127fn new(
1128 session: &Session,
1129 prev_graph_node_count: usize,
1130 encoder: FileEncoder,
1131 previous: Arc<SerializedDepGraph>,
1132 ) -> Self {
1133let mut stable_hasher = StableHasher::new();
1134previous.session_count().hash(&mut stable_hasher);
1135let anon_id_seed = stable_hasher.finish();
11361137#[cfg(debug_assertions)]
1138let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
1139Ok(s) => match EdgeFilter::new(&s) {
1140Ok(f) => Some(f),
1141Err(err) => {
::core::panicking::panic_fmt(format_args!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {0}",
err));
}panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
1142 },
1143Err(_) => None,
1144 };
11451146let new_node_count_estimate = 102 * prev_graph_node_count / 100 + 200;
11471148CurrentDepGraph {
1149 encoder: GraphEncoder::new(session, encoder, prev_graph_node_count, previous),
1150 anon_node_to_index: ShardedHashMap::with_capacity(
1151// FIXME: The count estimate is off as anon nodes are only a portion of the nodes.
1152new_node_count_estimate / sharded::shards(),
1153 ),
1154anon_id_seed,
1155#[cfg(debug_assertions)]
1156forbidden_edge,
1157#[cfg(debug_assertions)]
1158value_fingerprints: Lock::new(IndexVec::from_elem_n(None, new_node_count_estimate)),
1159 total_read_count: AtomicU64::new(0),
1160 total_duplicate_read_count: AtomicU64::new(0),
1161 }
1162 }
11631164#[cfg(debug_assertions)]
1165fn record_edge(
1166&self,
1167 dep_node_index: DepNodeIndex,
1168 key: DepNode,
1169 value_fingerprint: Fingerprint,
1170 ) {
1171if let Some(forbidden_edge) = &self.forbidden_edge {
1172forbidden_edge.index_to_node.lock().insert(dep_node_index, key);
1173 }
1174let prior_value_fingerprint = *self1175 .value_fingerprints
1176 .lock()
1177 .get_or_insert_with(dep_node_index, || value_fingerprint);
1178match (&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:?}");
1179 }
11801181/// Writes the node to the current dep-graph and allocates a `DepNodeIndex` for it.
1182 /// Assumes that this is a node that has no equivalent in the previous dep-graph.
1183#[inline(always)]
1184fn alloc_new_node(
1185&self,
1186 key: DepNode,
1187 edges: EdgesVec,
1188 value_fingerprint: Fingerprint,
1189 ) -> DepNodeIndex {
1190let dep_node_index = self.encoder.send_new(key, value_fingerprint, edges);
11911192#[cfg(debug_assertions)]
1193self.record_edge(dep_node_index, key, value_fingerprint);
11941195dep_node_index1196 }
1197}
11981199#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for TaskDepsRef<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TaskDepsRef::Allow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
&__self_0),
TaskDepsRef::EvalAlways =>
::core::fmt::Formatter::write_str(f, "EvalAlways"),
TaskDepsRef::Ignore =>
::core::fmt::Formatter::write_str(f, "Ignore"),
TaskDepsRef::Forbid =>
::core::fmt::Formatter::write_str(f, "Forbid"),
}
}
}Debug, #[automatically_derived]
impl<'a> ::core::clone::Clone for TaskDepsRef<'a> {
#[inline]
fn clone(&self) -> TaskDepsRef<'a> {
let _: ::core::clone::AssertParamIsClone<&'a Lock<TaskDeps>>;
*self
}
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for TaskDepsRef<'a> { }Copy)]
1200pub enum TaskDepsRef<'a> {
1201/// New dependencies can be added to the
1202 /// `TaskDeps`. This is used when executing a 'normal' query
1203 /// (no `eval_always` modifier)
1204Allow(&'a Lock<TaskDeps>),
1205/// This is used when executing an `eval_always` query. We don't
1206 /// need to track dependencies for a query that's always
1207 /// re-executed -- but we need to know that this is an `eval_always`
1208 /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE`
1209 /// when directly feeding other queries.
1210EvalAlways,
1211/// New dependencies are ignored. This is also used for `dep_graph.with_ignore`.
1212Ignore,
1213/// Any attempt to add new dependencies will cause a panic.
1214 /// This is used when decoding a query result from disk,
1215 /// to ensure that the decoding process doesn't itself
1216 /// require the execution of any queries.
1217Forbid,
1218}
12191220#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TaskDeps {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "TaskDeps",
"node", &self.node, "reads", &self.reads, "read_set",
&&self.read_set)
}
}Debug)]
1221pub struct TaskDeps {
1222#[cfg(debug_assertions)]
1223node: Option<DepNode>,
12241225/// A vector of `DepNodeIndex`, basically. Contains no duplicates.
1226reads: EdgesVec,
12271228/// When adding a new edge to `reads` in `DepGraph::read_index` we must determine if the edge
1229 /// has been seen before. We just do a linear scan of `reads` if its length is less than or
1230 /// equal to `LINEAR_SCAN_MAX`. Otherwise, we use this hashset for better performance. Note:
1231 /// `reads` is always the canonical edges representation; this field is just to speed up the
1232 /// seen-before test.
1233read_set: FxHashSet<DepNodeIndex>,
1234}
12351236impl TaskDeps {
1237/// See `TaskDeps::read_set` above.
1238const LINEAR_SCAN_MAX: usize = 16;
12391240#[inline]
1241fn new(#[cfg(debug_assertions)] node: Option<DepNode>, read_set_capacity: usize) -> Self {
1242TaskDeps {
1243#[cfg(debug_assertions)]
1244node,
1245 reads: EdgesVec::new(),
1246 read_set: FxHashSet::with_capacity_and_hasher(read_set_capacity, Default::default()),
1247 }
1248 }
1249}
12501251// A data structure that stores Option<DepNodeColor> values as a contiguous
1252// array, using one u32 per entry.
1253pub(super) struct DepNodeColorMap {
1254 values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1255}
12561257// All values below `COMPRESSED_RED` are green.
1258const COMPRESSED_RED: u32 = u32::MAX - 1;
1259const COMPRESSED_UNKNOWN: u32 = u32::MAX;
12601261impl DepNodeColorMap {
1262fn new(size: usize) -> DepNodeColorMap {
1263if 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);
1264DepNodeColorMap { values: (0..size).map(|_| AtomicU32::new(COMPRESSED_UNKNOWN)).collect() }
1265 }
12661267#[inline]
1268pub(super) fn current(&self, index: SerializedDepNodeIndex) -> Option<DepNodeIndex> {
1269let value = self.values[index].load(Ordering::Relaxed);
1270if value <= DepNodeIndex::MAX_AS_U32 { Some(DepNodeIndex::from_u32(value)) } else { None }
1271 }
12721273/// Atomically sets the color of a previous-session dep node to either green
1274 /// or red, if it has not already been colored.
1275 ///
1276 /// If the node already has a color, the new color is ignored, and the
1277 /// return value indicates the existing color.
1278#[inline(always)]
1279pub(super) fn try_set_color(
1280&self,
1281 prev_index: SerializedDepNodeIndex,
1282 color: DesiredColor,
1283 ) -> TrySetColorResult {
1284match self.values[prev_index].compare_exchange(
1285COMPRESSED_UNKNOWN,
1286match color {
1287 DesiredColor::Red => COMPRESSED_RED,
1288 DesiredColor::Green { index } => index.as_u32(),
1289 },
1290 Ordering::Relaxed,
1291 Ordering::Relaxed,
1292 ) {
1293Ok(_) => TrySetColorResult::Success,
1294Err(COMPRESSED_RED) => TrySetColorResult::AlreadyRed,
1295Err(index) => TrySetColorResult::AlreadyGreen { index: DepNodeIndex::from_u32(index) },
1296 }
1297 }
12981299#[inline]
1300pub(super) fn get(&self, index: SerializedDepNodeIndex) -> DepNodeColor {
1301let value = self.values[index].load(Ordering::Acquire);
1302// Green is by far the most common case. Check for that first so we can succeed with a
1303 // single comparison.
1304if value < COMPRESSED_RED {
1305 DepNodeColor::Green(DepNodeIndex::from_u32(value))
1306 } else if value == COMPRESSED_RED {
1307 DepNodeColor::Red1308 } else {
1309if 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);
1310 DepNodeColor::Unknown1311 }
1312 }
1313}
13141315/// The color that [`DepNodeColorMap::try_set_color`] should try to apply to a node.
1316#[derive(#[automatically_derived]
impl ::core::clone::Clone for DesiredColor {
#[inline]
fn clone(&self) -> DesiredColor {
let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DesiredColor { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for DesiredColor {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DesiredColor::Red => ::core::fmt::Formatter::write_str(f, "Red"),
DesiredColor::Green { index: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Green",
"index", &__self_0),
}
}
}Debug)]
1317pub(super) enum DesiredColor {
1318/// Try to mark the node red.
1319Red,
1320/// Try to mark the node green, associating it with a current-session node index.
1321Green { index: DepNodeIndex },
1322}
13231324/// Return value of [`DepNodeColorMap::try_set_color`], indicating success or failure,
1325/// and (on failure) what the existing color is.
1326#[derive(#[automatically_derived]
impl ::core::clone::Clone for TrySetColorResult {
#[inline]
fn clone(&self) -> TrySetColorResult {
let _: ::core::clone::AssertParamIsClone<DepNodeIndex>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrySetColorResult { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for TrySetColorResult {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TrySetColorResult::Success =>
::core::fmt::Formatter::write_str(f, "Success"),
TrySetColorResult::AlreadyRed =>
::core::fmt::Formatter::write_str(f, "AlreadyRed"),
TrySetColorResult::AlreadyGreen { index: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"AlreadyGreen", "index", &__self_0),
}
}
}Debug)]
1327pub(super) enum TrySetColorResult {
1328/// The [`DesiredColor`] was freshly applied to the node.
1329Success,
1330/// Coloring failed because the node was already marked red.
1331AlreadyRed,
1332/// Coloring failed because the node was already marked green,
1333 /// and corresponds to node `index` in the current-session dep graph.
1334AlreadyGreen { index: DepNodeIndex },
1335}
13361337#[inline(never)]
1338#[cold]
1339pub(crate) fn print_markframe_trace(graph: &DepGraph, frame: &MarkFrame<'_>) {
1340let data = graph.data.as_ref().unwrap();
13411342{
::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");
1343{ ::std::io::_eprint(format_args!("try_mark_green dep node stack:\n")); };eprintln!("try_mark_green dep node stack:");
13441345let mut i = 0;
1346let mut current = Some(frame);
1347while let Some(frame) = current {
1348let node = data.previous.index_to_node(frame.index);
1349{ ::std::io::_eprint(format_args!("#{0} {1:?}\n", i, node)); };eprintln!("#{i} {node:?}");
1350 current = frame.parent;
1351 i += 1;
1352 }
13531354{
::std::io::_eprint(format_args!("end of try_mark_green dep node stack\n"));
};eprintln!("end of try_mark_green dep node stack");
1355}
13561357#[cold]
1358#[inline(never)]
1359fn panic_on_forbidden_read(data: &DepGraphData, dep_node_index: DepNodeIndex) -> ! {
1360// We have to do an expensive reverse-lookup of the DepNode that
1361 // corresponds to `dep_node_index`, but that's OK since we are about
1362 // to ICE anyway.
1363let mut dep_node = None;
13641365// First try to find the dep node among those that already existed in the
1366 // previous session and has been marked green
1367for prev_index in data.colors.values.indices() {
1368if data.colors.current(prev_index) == Some(dep_node_index) {
1369 dep_node = Some(*data.previous.index_to_node(prev_index));
1370break;
1371 }
1372 }
13731374let dep_node = dep_node.map_or_else(
1375 || ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("with index {0:?}", dep_node_index))
})format!("with index {:?}", dep_node_index),
1376 |dep_node| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0:?}`", dep_node))
})format!("`{:?}`", dep_node),
1377 );
13781379{
::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!(
1380"Error: trying to record dependency on DepNode {dep_node} in a \
1381 context that does not allow it (e.g. during query deserialization). \
1382 The most common case of recording a dependency on a DepNode `foo` is \
1383 when the corresponding query `foo` is invoked. Invoking queries is not \
1384 allowed as part of loading something from the incremental on-disk cache. \
1385 See <https://github.com/rust-lang/rust/pull/91919>."
1386)1387}
13881389impl<'tcx> TyCtxt<'tcx> {
1390/// Return whether this kind always require evaluation.
1391#[inline(always)]
1392fn is_eval_always(self, kind: DepKind) -> bool {
1393self.dep_kind_vtable(kind).is_eval_always
1394 }
1395}