1 use errors::Diagnostic;
2 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_index::vec::{Idx, IndexVec};
5 use smallvec::SmallVec;
6 use rustc_data_structures::sync::{Lrc, Lock, AtomicU32, AtomicU64, Ordering};
7 use rustc_data_structures::sharded::{self, Sharded};
8 use std::sync::atomic::Ordering::SeqCst;
11 use std::collections::hash_map::Entry;
13 use crate::ty::{self, TyCtxt};
14 use parking_lot::{Mutex, Condvar};
16 use crate::ich::{StableHashingContext, StableHashingContextProvider, Fingerprint};
18 use super::debug::EdgeFilter;
19 use super::dep_node::{DepNode, DepKind, WorkProductId};
20 use super::query::DepGraphQuery;
21 use super::safe::DepGraphSafe;
22 use super::serialized::{SerializedDepGraph, SerializedDepNodeIndex};
23 use super::prev::PreviousDepGraph;
27 data: Option<Lrc<DepGraphData>>,
30 rustc_index::newtype_index! {
31 pub struct DepNodeIndex { .. }
35 pub const INVALID: DepNodeIndex = DepNodeIndex::MAX;
38 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
39 pub enum DepNodeColor {
45 pub fn is_green(self) -> bool {
47 DepNodeColor::Red => false,
48 DepNodeColor::Green(_) => true,
54 /// The new encoding of the dependency graph, optimized for red/green
55 /// tracking. The `current` field is the dependency graph of only the
56 /// current compilation session: We don't merge the previous dep-graph into
57 /// current one anymore.
58 current: CurrentDepGraph,
60 /// The dep-graph from the previous compilation session. It contains all
61 /// nodes and edges as well as all fingerprints of nodes that have them.
62 previous: PreviousDepGraph,
64 colors: DepNodeColorMap,
66 /// A set of loaded diagnostics that is in the progress of being emitted.
67 emitting_diagnostics: Mutex<FxHashSet<DepNodeIndex>>,
69 /// Used to wait for diagnostics to be emitted.
70 emitting_diagnostics_cond_var: Condvar,
72 /// When we load, there may be `.o` files, cached MIR, or other such
73 /// things available to us. If we find that they are not dirty, we
74 /// load the path to the file storing those work-products here into
75 /// this map. We can later look for and extract that data.
76 previous_work_products: FxHashMap<WorkProductId, WorkProduct>,
78 dep_node_debug: Lock<FxHashMap<DepNode, String>>,
81 pub fn hash_result<R>(hcx: &mut StableHashingContext<'_>, result: &R) -> Option<Fingerprint>
83 R: for<'a> HashStable<StableHashingContext<'a>>,
85 let mut stable_hasher = StableHasher::new();
86 result.hash_stable(hcx, &mut stable_hasher);
88 Some(stable_hasher.finish())
92 pub fn new(prev_graph: PreviousDepGraph,
93 prev_work_products: FxHashMap<WorkProductId, WorkProduct>) -> DepGraph {
94 let prev_graph_node_count = prev_graph.node_count();
97 data: Some(Lrc::new(DepGraphData {
98 previous_work_products: prev_work_products,
99 dep_node_debug: Default::default(),
100 current: CurrentDepGraph::new(prev_graph_node_count),
101 emitting_diagnostics: Default::default(),
102 emitting_diagnostics_cond_var: Condvar::new(),
103 previous: prev_graph,
104 colors: DepNodeColorMap::new(prev_graph_node_count),
109 pub fn new_disabled() -> DepGraph {
115 /// Returns `true` if we are actually building the full dep-graph, and `false` otherwise.
117 pub fn is_fully_enabled(&self) -> bool {
121 pub fn query(&self) -> DepGraphQuery {
122 let data = self.data.as_ref().unwrap().current.data.lock();
123 let nodes: Vec<_> = data.iter().map(|n| n.node).collect();
124 let mut edges = Vec::new();
125 for (from, edge_targets) in data.iter().map(|d| (d.node, &d.edges)) {
126 for &edge_target in edge_targets.iter() {
127 let to = data[edge_target].node;
128 edges.push((from, to));
132 DepGraphQuery::new(&nodes[..], &edges[..])
135 pub fn assert_ignored(&self)
137 if let Some(..) = self.data {
138 ty::tls::with_context_opt(|icx| {
139 let icx = if let Some(icx) = icx { icx } else { return };
140 assert!(icx.task_deps.is_none(), "expected no task dependency tracking");
145 pub fn with_ignore<OP,R>(&self, op: OP) -> R
146 where OP: FnOnce() -> R
148 ty::tls::with_context(|icx| {
149 let icx = ty::tls::ImplicitCtxt {
154 ty::tls::enter_context(&icx, |_| {
160 /// Starts a new dep-graph task. Dep-graph tasks are specified
161 /// using a free function (`task`) and **not** a closure -- this
162 /// is intentional because we want to exercise tight control over
163 /// what state they have access to. In particular, we want to
164 /// prevent implicit 'leaks' of tracked state into the task (which
165 /// could then be read without generating correct edges in the
166 /// dep-graph -- see the [rustc guide] for more details on
167 /// the dep-graph). To this end, the task function gets exactly two
168 /// pieces of state: the context `cx` and an argument `arg`. Both
169 /// of these bits of state must be of some type that implements
170 /// `DepGraphSafe` and hence does not leak.
172 /// The choice of two arguments is not fundamental. One argument
173 /// would work just as well, since multiple values can be
174 /// collected using tuples. However, using two arguments works out
175 /// to be quite convenient, since it is common to need a context
176 /// (`cx`) and some argument (e.g., a `DefId` identifying what
177 /// item to process).
179 /// For cases where you need some other number of arguments:
181 /// - If you only need one argument, just use `()` for the `arg`
183 /// - If you need 3+ arguments, use a tuple for the
186 /// [rustc guide]: https://rust-lang.github.io/rustc-guide/incremental-compilation.html
187 pub fn with_task<'a, C, A, R>(
193 hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
194 ) -> (R, DepNodeIndex)
196 C: DepGraphSafe + StableHashingContextProvider<'a>,
198 self.with_task_impl(key, cx, arg, false, task,
199 |_key| Some(TaskDeps {
200 #[cfg(debug_assertions)]
202 reads: SmallVec::new(),
203 read_set: Default::default(),
205 |data, key, fingerprint, task| {
206 data.complete_task(key, task.unwrap(), fingerprint)
211 /// Creates a new dep-graph input with value `input`
212 pub fn input_task<'a, C, R>(&self,
217 where C: DepGraphSafe + StableHashingContextProvider<'a>,
218 R: for<'b> HashStable<StableHashingContext<'b>>,
220 fn identity_fn<C, A>(_: C, arg: A) -> A {
224 self.with_task_impl(key, cx, input, true, identity_fn,
226 |data, key, fingerprint, _| {
227 data.alloc_node(key, SmallVec::new(), fingerprint)
232 fn with_task_impl<'a, C, A, R>(
239 create_task: fn(DepNode) -> Option<TaskDeps>,
240 finish_task_and_alloc_depnode: fn(&CurrentDepGraph,
243 Option<TaskDeps>) -> DepNodeIndex,
244 hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
245 ) -> (R, DepNodeIndex)
247 C: DepGraphSafe + StableHashingContextProvider<'a>,
249 if let Some(ref data) = self.data {
250 let task_deps = create_task(key).map(|deps| Lock::new(deps));
252 // In incremental mode, hash the result of the task. We don't
253 // do anything with the hash yet, but we are computing it
255 // - we make sure that the infrastructure works and
256 // - we can get an idea of the runtime cost.
257 let mut hcx = cx.get_stable_hashing_context();
259 let result = if no_tcx {
262 ty::tls::with_context(|icx| {
263 let icx = ty::tls::ImplicitCtxt {
264 task_deps: task_deps.as_ref(),
268 ty::tls::enter_context(&icx, |_| {
274 let current_fingerprint = hash_result(&mut hcx, &result);
276 let dep_node_index = finish_task_and_alloc_depnode(
279 current_fingerprint.unwrap_or(Fingerprint::ZERO),
280 task_deps.map(|lock| lock.into_inner()),
283 let print_status = cfg!(debug_assertions) && hcx.sess().opts.debugging_opts.dep_tasks;
285 // Determine the color of the new DepNode.
286 if let Some(prev_index) = data.previous.node_to_index_opt(&key) {
287 let prev_fingerprint = data.previous.fingerprint_by_index(prev_index);
289 let color = if let Some(current_fingerprint) = current_fingerprint {
290 if current_fingerprint == prev_fingerprint {
292 eprintln!("[task::green] {:?}", key);
294 DepNodeColor::Green(dep_node_index)
297 eprintln!("[task::red] {:?}", key);
303 eprintln!("[task::unknown] {:?}", key);
305 // Mark the node as Red if we can't hash the result
309 debug_assert!(data.colors.get(prev_index).is_none(),
310 "DepGraph::with_task() - Duplicate DepNodeColor \
311 insertion for {:?}", key);
313 data.colors.insert(prev_index, color);
316 eprintln!("[task::new] {:?}", key);
320 (result, dep_node_index)
322 (task(cx, arg), DepNodeIndex::INVALID)
326 /// Executes something within an "anonymous" task, that is, a task the
327 /// `DepNode` of which is determined by the list of inputs it read from.
328 pub fn with_anon_task<OP,R>(&self, dep_kind: DepKind, op: OP) -> (R, DepNodeIndex)
329 where OP: FnOnce() -> R
331 if let Some(ref data) = self.data {
332 let (result, task_deps) = ty::tls::with_context(|icx| {
333 let task_deps = Lock::new(TaskDeps {
334 #[cfg(debug_assertions)]
336 reads: SmallVec::new(),
337 read_set: Default::default(),
341 let icx = ty::tls::ImplicitCtxt {
342 task_deps: Some(&task_deps),
346 ty::tls::enter_context(&icx, |_| {
351 (r, task_deps.into_inner())
353 let dep_node_index = data.current
354 .complete_anon_task(dep_kind, task_deps);
355 (result, dep_node_index)
357 (op(), DepNodeIndex::INVALID)
361 /// Executes something within an "eval-always" task which is a task
362 /// that runs whenever anything changes.
363 pub fn with_eval_always_task<'a, C, A, R>(
369 hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
370 ) -> (R, DepNodeIndex)
372 C: DepGraphSafe + StableHashingContextProvider<'a>,
374 self.with_task_impl(key, cx, arg, false, task,
376 |data, key, fingerprint, _| {
377 data.alloc_node(key, smallvec![], fingerprint)
383 pub fn read(&self, v: DepNode) {
384 if let Some(ref data) = self.data {
385 let map = data.current.node_to_node_index.get_shard_by_value(&v).lock();
386 if let Some(dep_node_index) = map.get(&v).copied() {
388 data.read_index(dep_node_index);
390 bug!("DepKind {:?} should be pre-allocated but isn't.", v.kind)
396 pub fn read_index(&self, dep_node_index: DepNodeIndex) {
397 if let Some(ref data) = self.data {
398 data.read_index(dep_node_index);
403 pub fn dep_node_index_of(&self, dep_node: &DepNode) -> DepNodeIndex {
409 .get_shard_by_value(dep_node)
417 pub fn dep_node_exists(&self, dep_node: &DepNode) -> bool {
418 if let Some(ref data) = self.data {
421 .get_shard_by_value(&dep_node)
423 .contains_key(dep_node)
430 pub fn fingerprint_of(&self, dep_node_index: DepNodeIndex) -> Fingerprint {
431 let data = self.data.as_ref().expect("dep graph enabled").current.data.lock();
432 data[dep_node_index].fingerprint
435 pub fn prev_fingerprint_of(&self, dep_node: &DepNode) -> Option<Fingerprint> {
436 self.data.as_ref().unwrap().previous.fingerprint_of(dep_node)
440 pub fn prev_dep_node_index_of(&self, dep_node: &DepNode) -> SerializedDepNodeIndex {
441 self.data.as_ref().unwrap().previous.node_to_index(dep_node)
444 /// Checks whether a previous work product exists for `v` and, if
445 /// so, return the path that leads to it. Used to skip doing work.
446 pub fn previous_work_product(&self, v: &WorkProductId) -> Option<WorkProduct> {
450 data.previous_work_products.get(v).cloned()
454 /// Access the map of work-products created during the cached run. Only
455 /// used during saving of the dep-graph.
456 pub fn previous_work_products(&self) -> &FxHashMap<WorkProductId, WorkProduct> {
457 &self.data.as_ref().unwrap().previous_work_products
461 pub fn register_dep_node_debug_str<F>(&self,
464 where F: FnOnce() -> String
466 let dep_node_debug = &self.data.as_ref().unwrap().dep_node_debug;
468 if dep_node_debug.borrow().contains_key(&dep_node) {
471 let debug_str = debug_str_gen();
472 dep_node_debug.borrow_mut().insert(dep_node, debug_str);
475 pub(super) fn dep_node_debug_str(&self, dep_node: DepNode) -> Option<String> {
484 pub fn edge_deduplication_data(&self) -> Option<(u64, u64)> {
485 if cfg!(debug_assertions) {
486 let current_dep_graph = &self.data.as_ref().unwrap().current;
488 Some((current_dep_graph.total_read_count.load(SeqCst),
489 current_dep_graph.total_duplicate_read_count.load(SeqCst)))
495 pub fn serialize(&self) -> SerializedDepGraph {
496 let data = self.data.as_ref().unwrap().current.data.lock();
498 let fingerprints: IndexVec<SerializedDepNodeIndex, _> =
499 data.iter().map(|d| d.fingerprint).collect();
500 let nodes: IndexVec<SerializedDepNodeIndex, _> =
501 data.iter().map(|d| d.node).collect();
503 let total_edge_count: usize = data.iter().map(|d| d.edges.len()).sum();
505 let mut edge_list_indices = IndexVec::with_capacity(nodes.len());
506 let mut edge_list_data = Vec::with_capacity(total_edge_count);
508 for (current_dep_node_index, edges) in data.iter_enumerated().map(|(i, d)| (i, &d.edges)) {
509 let start = edge_list_data.len() as u32;
510 // This should really just be a memcpy :/
511 edge_list_data.extend(edges.iter().map(|i| SerializedDepNodeIndex::new(i.index())));
512 let end = edge_list_data.len() as u32;
514 debug_assert_eq!(current_dep_node_index.index(), edge_list_indices.len());
515 edge_list_indices.push((start, end));
518 debug_assert!(edge_list_data.len() <= ::std::u32::MAX as usize);
519 debug_assert_eq!(edge_list_data.len(), total_edge_count);
529 pub fn node_color(&self, dep_node: &DepNode) -> Option<DepNodeColor> {
530 if let Some(ref data) = self.data {
531 if let Some(prev_index) = data.previous.node_to_index_opt(dep_node) {
532 return data.colors.get(prev_index)
534 // This is a node that did not exist in the previous compilation
535 // session, so we consider it to be red.
536 return Some(DepNodeColor::Red)
543 /// Try to read a node index for the node dep_node.
544 /// A node will have an index, when it's already been marked green, or when we can mark it
545 /// green. This function will mark the current task as a reader of the specified node, when
546 /// a node index can be found for that node.
547 pub fn try_mark_green_and_read(
551 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
552 self.try_mark_green(tcx, dep_node).map(|(prev_index, dep_node_index)| {
553 debug_assert!(self.is_green(&dep_node));
554 self.read_index(dep_node_index);
555 (prev_index, dep_node_index)
559 pub fn try_mark_green(
563 ) -> Option<(SerializedDepNodeIndex, DepNodeIndex)> {
564 debug_assert!(!dep_node.kind.is_eval_always());
566 // Return None if the dep graph is disabled
567 let data = self.data.as_ref()?;
569 // Return None if the dep node didn't exist in the previous session
570 let prev_index = data.previous.node_to_index_opt(dep_node)?;
572 match data.colors.get(prev_index) {
573 Some(DepNodeColor::Green(dep_node_index)) => Some((prev_index, dep_node_index)),
574 Some(DepNodeColor::Red) => None,
576 // This DepNode and the corresponding query invocation existed
577 // in the previous compilation session too, so we can try to
578 // mark it as green by recursively marking all of its
579 // dependencies green.
580 self.try_mark_previous_green(
585 ).map(|dep_node_index| {
586 (prev_index, dep_node_index)
592 /// Try to mark a dep-node which existed in the previous compilation session as green.
593 fn try_mark_previous_green<'tcx>(
597 prev_dep_node_index: SerializedDepNodeIndex,
599 ) -> Option<DepNodeIndex> {
600 debug!("try_mark_previous_green({:?}) - BEGIN", dep_node);
602 #[cfg(not(parallel_compiler))]
604 debug_assert!(!data.current
606 .get_shard_by_value(dep_node)
608 .contains_key(dep_node));
609 debug_assert!(data.colors.get(prev_dep_node_index).is_none());
612 // We never try to mark eval_always nodes as green
613 debug_assert!(!dep_node.kind.is_eval_always());
615 debug_assert_eq!(data.previous.index_to_node(prev_dep_node_index), *dep_node);
617 let prev_deps = data.previous.edge_targets_from(prev_dep_node_index);
619 let mut current_deps = SmallVec::new();
621 for &dep_dep_node_index in prev_deps {
622 let dep_dep_node_color = data.colors.get(dep_dep_node_index);
624 match dep_dep_node_color {
625 Some(DepNodeColor::Green(node_index)) => {
626 // This dependency has been marked as green before, we are
627 // still fine and can continue with checking the other
629 debug!("try_mark_previous_green({:?}) --- found dependency {:?} to \
630 be immediately green",
632 data.previous.index_to_node(dep_dep_node_index));
633 current_deps.push(node_index);
635 Some(DepNodeColor::Red) => {
636 // We found a dependency the value of which has changed
637 // compared to the previous compilation session. We cannot
638 // mark the DepNode as green and also don't need to bother
639 // with checking any of the other dependencies.
640 debug!("try_mark_previous_green({:?}) - END - dependency {:?} was \
643 data.previous.index_to_node(dep_dep_node_index));
647 let dep_dep_node = &data.previous.index_to_node(dep_dep_node_index);
649 // We don't know the state of this dependency. If it isn't
650 // an eval_always node, let's try to mark it green recursively.
651 if !dep_dep_node.kind.is_eval_always() {
652 debug!("try_mark_previous_green({:?}) --- state of dependency {:?} \
653 is unknown, trying to mark it green", dep_node,
656 let node_index = self.try_mark_previous_green(
662 if let Some(node_index) = node_index {
663 debug!("try_mark_previous_green({:?}) --- managed to MARK \
664 dependency {:?} as green", dep_node, dep_dep_node);
665 current_deps.push(node_index);
669 match dep_dep_node.kind {
672 DepKind::CrateMetadata => {
673 if dep_dep_node.extract_def_id(tcx).is_none() {
674 // If the node does not exist anymore, we
675 // just fail to mark green.
678 // If the node does exist, it should have
679 // been pre-allocated.
680 bug!("DepNode {:?} should have been \
681 pre-allocated but wasn't.",
686 // For other kinds of nodes it's OK to be
692 // We failed to mark it green, so we try to force the query.
693 debug!("try_mark_previous_green({:?}) --- trying to force \
694 dependency {:?}", dep_node, dep_dep_node);
695 if crate::ty::query::force_from_dep_node(tcx, dep_dep_node) {
696 let dep_dep_node_color = data.colors.get(dep_dep_node_index);
698 match dep_dep_node_color {
699 Some(DepNodeColor::Green(node_index)) => {
700 debug!("try_mark_previous_green({:?}) --- managed to \
701 FORCE dependency {:?} to green",
702 dep_node, dep_dep_node);
703 current_deps.push(node_index);
705 Some(DepNodeColor::Red) => {
706 debug!("try_mark_previous_green({:?}) - END - \
707 dependency {:?} was red after forcing",
713 if !tcx.sess.has_errors() {
714 bug!("try_mark_previous_green() - Forcing the DepNode \
715 should have set its color")
717 // If the query we just forced has resulted
718 // in some kind of compilation error, we
719 // don't expect that the corresponding
720 // dep-node color has been updated.
725 // The DepNode could not be forced.
726 debug!("try_mark_previous_green({:?}) - END - dependency {:?} \
727 could not be forced", dep_node, dep_dep_node);
734 // If we got here without hitting a `return` that means that all
735 // dependencies of this DepNode could be marked as green. Therefore we
736 // can also mark this DepNode as green.
738 // There may be multiple threads trying to mark the same dep node green concurrently
740 let dep_node_index = {
741 // Copy the fingerprint from the previous graph,
742 // so we don't have to recompute it
743 let fingerprint = data.previous.fingerprint_by_index(prev_dep_node_index);
745 // We allocating an entry for the node in the current dependency graph and
746 // adding all the appropriate edges imported from the previous graph
747 data.current.intern_node(*dep_node, current_deps, fingerprint)
750 // ... emitting any stored diagnostic ...
752 // FIXME: Store the fact that a node has diagnostics in a bit in the dep graph somewhere
753 // Maybe store a list on disk and encode this fact in the DepNodeState
754 let diagnostics = tcx.queries.on_disk_cache
755 .load_diagnostics(tcx, prev_dep_node_index);
757 #[cfg(not(parallel_compiler))]
758 debug_assert!(data.colors.get(prev_dep_node_index).is_none(),
759 "DepGraph::try_mark_previous_green() - Duplicate DepNodeColor \
760 insertion for {:?}", dep_node);
762 if unlikely!(diagnostics.len() > 0) {
763 self.emit_diagnostics(
772 // ... and finally storing a "Green" entry in the color map.
773 // Multiple threads can all write the same color here
774 data.colors.insert(prev_dep_node_index, DepNodeColor::Green(dep_node_index));
776 debug!("try_mark_previous_green({:?}) - END - successfully marked as green", dep_node);
780 /// Atomically emits some loaded diagnostics.
781 /// This may be called concurrently on multiple threads for the same dep node.
784 fn emit_diagnostics<'tcx>(
788 dep_node_index: DepNodeIndex,
789 prev_dep_node_index: SerializedDepNodeIndex,
790 diagnostics: Vec<Diagnostic>,
792 let mut emitting = data.emitting_diagnostics.lock();
794 if data.colors.get(prev_dep_node_index) == Some(DepNodeColor::Green(dep_node_index)) {
795 // The node is already green so diagnostics must have been emitted already
799 if emitting.insert(dep_node_index) {
800 // We were the first to insert the node in the set so this thread
801 // must emit the diagnostics and signal other potentially waiting
805 // Promote the previous diagnostics to the current session.
806 tcx.queries.on_disk_cache
807 .store_diagnostics(dep_node_index, diagnostics.clone().into());
809 let handle = tcx.sess.diagnostic();
811 for diagnostic in diagnostics {
812 handle.emit_diagnostic(&diagnostic);
815 // Mark the node as green now that diagnostics are emitted
816 data.colors.insert(prev_dep_node_index, DepNodeColor::Green(dep_node_index));
818 // Remove the node from the set
819 data.emitting_diagnostics.lock().remove(&dep_node_index);
822 data.emitting_diagnostics_cond_var.notify_all();
824 // We must wait for the other thread to finish emitting the diagnostic
827 data.emitting_diagnostics_cond_var.wait(&mut emitting);
829 .get(prev_dep_node_index) == Some(DepNodeColor::Green(dep_node_index)) {
836 // Returns true if the given node has been marked as green during the
837 // current compilation session. Used in various assertions
838 pub fn is_green(&self, dep_node: &DepNode) -> bool {
839 self.node_color(dep_node).map(|c| c.is_green()).unwrap_or(false)
842 // This method loads all on-disk cacheable query results into memory, so
843 // they can be written out to the new cache file again. Most query results
844 // will already be in memory but in the case where we marked something as
845 // green but then did not need the value, that value will never have been
848 // This method will only load queries that will end up in the disk cache.
849 // Other queries will not be executed.
850 pub fn exec_cache_promotions(&self, tcx: TyCtxt<'_>) {
851 let _prof_timer = tcx.prof.generic_activity("incr_comp_query_cache_promotion");
853 let data = self.data.as_ref().unwrap();
854 for prev_index in data.colors.values.indices() {
855 match data.colors.get(prev_index) {
856 Some(DepNodeColor::Green(_)) => {
857 let dep_node = data.previous.index_to_node(prev_index);
858 dep_node.try_load_from_on_disk_cache(tcx);
861 Some(DepNodeColor::Red) => {
862 // We can skip red nodes because a node can only be marked
863 // as red if the query result was recomputed and thus is
864 // already in memory.
871 /// A "work product" is an intermediate result that we save into the
872 /// incremental directory for later re-use. The primary example are
873 /// the object files that we save for each partition at code
876 /// Each work product is associated with a dep-node, representing the
877 /// process that produced the work-product. If that dep-node is found
878 /// to be dirty when we load up, then we will delete the work-product
879 /// at load time. If the work-product is found to be clean, then we
880 /// will keep a record in the `previous_work_products` list.
882 /// In addition, work products have an associated hash. This hash is
883 /// an extra hash that can be used to decide if the work-product from
884 /// a previous compilation can be re-used (in addition to the dirty
887 /// As the primary example, consider the object files we generate for
888 /// each partition. In the first run, we create partitions based on
889 /// the symbols that need to be compiled. For each partition P, we
890 /// hash the symbols in P and create a `WorkProduct` record associated
891 /// with `DepNode::CodegenUnit(P)`; the hash is the set of symbols
894 /// The next time we compile, if the `DepNode::CodegenUnit(P)` is
895 /// judged to be clean (which means none of the things we read to
896 /// generate the partition were found to be dirty), it will be loaded
897 /// into previous work products. We will then regenerate the set of
898 /// symbols in the partition P and hash them (note that new symbols
899 /// may be added -- for example, new monomorphizations -- even if
900 /// nothing in P changed!). We will compare that hash against the
901 /// previous hash. If it matches up, we can reuse the object file.
902 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
903 pub struct WorkProduct {
904 pub cgu_name: String,
905 /// Saved files associated with this CGU.
906 pub saved_files: Vec<(WorkProductFileKind, String)>,
909 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, PartialEq)]
910 pub enum WorkProductFileKind {
919 edges: SmallVec<[DepNodeIndex; 8]>,
920 fingerprint: Fingerprint,
923 /// `CurrentDepGraph` stores the dependency graph for the current session.
924 /// It will be populated as we run queries or tasks.
926 /// The nodes in it are identified by an index (`DepNodeIndex`).
927 /// The data for each node is stored in its `DepNodeData`, found in the `data` field.
929 /// We never remove nodes from the graph: they are only added.
931 /// This struct uses two locks internally. The `data` and `node_to_node_index` fields are
932 /// locked separately. Operations that take a `DepNodeIndex` typically just access
935 /// The only operation that must manipulate both locks is adding new nodes, in which case
936 /// we first acquire the `node_to_node_index` lock and then, once a new node is to be inserted,
937 /// acquire the lock on `data.`
938 pub(super) struct CurrentDepGraph {
939 data: Lock<IndexVec<DepNodeIndex, DepNodeData>>,
940 node_to_node_index: Sharded<FxHashMap<DepNode, DepNodeIndex>>,
942 /// Used to trap when a specific edge is added to the graph.
943 /// This is used for debug purposes and is only active with `debug_assertions`.
945 forbidden_edge: Option<EdgeFilter>,
947 /// Anonymous `DepNode`s are nodes whose IDs we compute from the list of
948 /// their edges. This has the beneficial side-effect that multiple anonymous
949 /// nodes can be coalesced into one without changing the semantics of the
950 /// dependency graph. However, the merging of nodes can lead to a subtle
951 /// problem during red-green marking: The color of an anonymous node from
952 /// the current session might "shadow" the color of the node with the same
953 /// ID from the previous session. In order to side-step this problem, we make
954 /// sure that anonymous `NodeId`s allocated in different sessions don't overlap.
955 /// This is implemented by mixing a session-key into the ID fingerprint of
956 /// each anon node. The session-key is just a random number generated when
957 /// the `DepGraph` is created.
958 anon_id_seed: Fingerprint,
960 /// These are simple counters that are for profiling and
961 /// debugging and only active with `debug_assertions`.
962 total_read_count: AtomicU64,
963 total_duplicate_read_count: AtomicU64,
966 impl CurrentDepGraph {
967 fn new(prev_graph_node_count: usize) -> CurrentDepGraph {
968 use std::time::{SystemTime, UNIX_EPOCH};
970 let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
971 let nanos = duration.as_secs() * 1_000_000_000 +
972 duration.subsec_nanos() as u64;
973 let mut stable_hasher = StableHasher::new();
974 nanos.hash(&mut stable_hasher);
976 let forbidden_edge = if cfg!(debug_assertions) {
977 match env::var("RUST_FORBID_DEP_GRAPH_EDGE") {
979 match EdgeFilter::new(&s) {
981 Err(err) => bug!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err),
990 // Pre-allocate the dep node structures. We over-allocate a little so
991 // that we hopefully don't have to re-allocate during this compilation
992 // session. The over-allocation is 2% plus a small constant to account
993 // for the fact that in very small crates 2% might not be enough.
994 let new_node_count_estimate = (prev_graph_node_count * 102) / 100 + 200;
997 data: Lock::new(IndexVec::with_capacity(new_node_count_estimate)),
998 node_to_node_index: Sharded::new(|| FxHashMap::with_capacity_and_hasher(
999 new_node_count_estimate / sharded::SHARDS,
1002 anon_id_seed: stable_hasher.finish(),
1004 total_read_count: AtomicU64::new(0),
1005 total_duplicate_read_count: AtomicU64::new(0),
1012 task_deps: TaskDeps,
1013 fingerprint: Fingerprint
1015 self.alloc_node(node, task_deps.reads, fingerprint)
1018 fn complete_anon_task(&self, kind: DepKind, task_deps: TaskDeps) -> DepNodeIndex {
1019 debug_assert!(!kind.is_eval_always());
1021 let mut hasher = StableHasher::new();
1023 // The dep node indices are hashed here instead of hashing the dep nodes of the
1024 // dependencies. These indices may refer to different nodes per session, but this isn't
1025 // a problem here because we that ensure the final dep node hash is per session only by
1026 // combining it with the per session random number `anon_id_seed`. This hash only need
1027 // to map the dependencies to a single value on a per session basis.
1028 task_deps.reads.hash(&mut hasher);
1030 let target_dep_node = DepNode {
1033 // Fingerprint::combine() is faster than sending Fingerprint
1034 // through the StableHasher (at least as long as StableHasher
1036 hash: self.anon_id_seed.combine(hasher.finish()),
1039 self.intern_node(target_dep_node, task_deps.reads, Fingerprint::ZERO)
1045 edges: SmallVec<[DepNodeIndex; 8]>,
1046 fingerprint: Fingerprint
1048 debug_assert!(!self.node_to_node_index
1049 .get_shard_by_value(&dep_node)
1051 .contains_key(&dep_node));
1052 self.intern_node(dep_node, edges, fingerprint)
1058 edges: SmallVec<[DepNodeIndex; 8]>,
1059 fingerprint: Fingerprint
1061 match self.node_to_node_index.get_shard_by_value(&dep_node).lock().entry(dep_node) {
1062 Entry::Occupied(entry) => *entry.get(),
1063 Entry::Vacant(entry) => {
1064 let mut data = self.data.lock();
1065 let dep_node_index = DepNodeIndex::new(data.len());
1066 data.push(DepNodeData {
1071 entry.insert(dep_node_index);
1079 fn read_index(&self, source: DepNodeIndex) {
1080 ty::tls::with_context_opt(|icx| {
1081 let icx = if let Some(icx) = icx { icx } else { return };
1082 if let Some(task_deps) = icx.task_deps {
1083 let mut task_deps = task_deps.lock();
1084 if cfg!(debug_assertions) {
1085 self.current.total_read_count.fetch_add(1, SeqCst);
1087 if task_deps.read_set.insert(source) {
1088 task_deps.reads.push(source);
1090 #[cfg(debug_assertions)]
1092 if let Some(target) = task_deps.node {
1093 let data = self.current.data.lock();
1094 if let Some(ref forbidden_edge) = self.current.forbidden_edge {
1095 let source = data[source].node;
1096 if forbidden_edge.test(&source, &target) {
1097 bug!("forbidden edge {:?} -> {:?} created",
1104 } else if cfg!(debug_assertions) {
1105 self.current.total_duplicate_read_count.fetch_add(1, SeqCst);
1112 pub struct TaskDeps {
1113 #[cfg(debug_assertions)]
1114 node: Option<DepNode>,
1115 reads: SmallVec<[DepNodeIndex; 8]>,
1116 read_set: FxHashSet<DepNodeIndex>,
1119 // A data structure that stores Option<DepNodeColor> values as a contiguous
1120 // array, using one u32 per entry.
1121 struct DepNodeColorMap {
1122 values: IndexVec<SerializedDepNodeIndex, AtomicU32>,
1125 const COMPRESSED_NONE: u32 = 0;
1126 const COMPRESSED_RED: u32 = 1;
1127 const COMPRESSED_FIRST_GREEN: u32 = 2;
1129 impl DepNodeColorMap {
1130 fn new(size: usize) -> DepNodeColorMap {
1132 values: (0..size).map(|_| AtomicU32::new(COMPRESSED_NONE)).collect(),
1136 fn get(&self, index: SerializedDepNodeIndex) -> Option<DepNodeColor> {
1137 match self.values[index].load(Ordering::Acquire) {
1138 COMPRESSED_NONE => None,
1139 COMPRESSED_RED => Some(DepNodeColor::Red),
1140 value => Some(DepNodeColor::Green(DepNodeIndex::from_u32(
1141 value - COMPRESSED_FIRST_GREEN
1146 fn insert(&self, index: SerializedDepNodeIndex, color: DepNodeColor) {
1147 self.values[index].store(match color {
1148 DepNodeColor::Red => COMPRESSED_RED,
1149 DepNodeColor::Green(index) => index.as_u32() + COMPRESSED_FIRST_GREEN,
1150 }, Ordering::Release)