Skip to main content

rustc_incremental/persist/
load.rs

1//! Code to load the dep-graph from files.
2
3use std::io;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use rustc_data_structures::unord::UnordMap;
8use rustc_hashes::Hash64;
9use rustc_middle::dep_graph::{DepGraph, SerializedDepGraph, WorkProductMap};
10use rustc_middle::query::on_disk_cache::OnDiskCache;
11use rustc_serialize::opaque::{FileEncoder, MemDecoder};
12use rustc_serialize::{Decodable, Encodable};
13use rustc_session::config::IncrementalStateAssertion;
14use rustc_session::{IncrCompSession, Session, StableCrateId};
15use rustc_span::Symbol;
16use tracing::{debug, warn};
17
18use super::data::*;
19use super::file_format;
20use super::fs::*;
21use crate::diagnostics;
22use crate::persist::file_format::{OpenFile, OpenFileError};
23
24#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LoadResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Ok { prev_graph: __self_0, prev_work_products: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f, "Ok",
                    "prev_graph", __self_0, "prev_work_products", &__self_1),
            Self::DataOutOfDate =>
                ::core::fmt::Formatter::write_str(f, "DataOutOfDate"),
            Self::IoError { path: __self_0, err: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "IoError", "path", __self_0, "err", &__self_1),
        }
    }
}Debug)]
25/// Represents the result of an attempt to load incremental compilation data.
26enum LoadResult {
27    /// Loading was successful.
28    Ok { prev_graph: Arc<SerializedDepGraph>, prev_work_products: WorkProductMap },
29    /// The file either didn't exist or was produced by an incompatible compiler version.
30    DataOutOfDate,
31    /// Loading failed due to an unexpected I/O error.
32    IoError { path: PathBuf, err: io::Error },
33}
34
35fn load_dep_graph(sess: &Session, incr_comp_session: &IncrCompSession) -> LoadResult {
36    if !sess.opts.incremental.is_some() {
    ::core::panicking::panic("assertion failed: sess.opts.incremental.is_some()")
};assert!(sess.opts.incremental.is_some());
37
38    let _timer = sess.prof.generic_activity("incr_comp_prepare_load_dep_graph");
39
40    // Calling `sess.incr_comp_session_dir()` will panic if `sess.opts.incremental.is_none()`.
41    // Fortunately, we just checked that this isn't the case.
42    let Some(path) = old_dep_graph_path(incr_comp_session) else {
43        return LoadResult::DataOutOfDate;
44    };
45    let expected_hash = sess.opts.dep_tracking_hash(false);
46
47    let mut prev_work_products = UnordMap::default();
48
49    let Some(work_products_path) = old_work_products_path(incr_comp_session) else {
50        return LoadResult::DataOutOfDate;
51    };
52
53    if let Ok(OpenFile { mmap, start_pos }) =
54        file_format::open_incremental_file(sess, &work_products_path)
55    {
56        // Decode the list of work_products
57        let Ok(mut work_product_decoder) = MemDecoder::new(&mmap[..], start_pos) else {
58            sess.dcx().emit_warn(diagnostics::CorruptFile { path: &work_products_path });
59            return LoadResult::DataOutOfDate;
60        };
61        let work_products: Vec<SerializedWorkProduct> =
62            Decodable::decode(&mut work_product_decoder);
63
64        for swp in work_products {
65            let all_files_exist = swp.work_product.saved_files.items().all(|(_, path)| {
66                let exists = in_old_incr_comp_dir_sess(incr_comp_session, path).unwrap().exists();
67                if !exists && sess.opts.unstable_opts.incremental_info {
68                    {
    ::std::io::_eprint(format_args!("incremental: could not find file for work product: {0}\n",
            path));
};eprintln!("incremental: could not find file for work product: {path}",);
69                }
70                exists
71            });
72
73            if all_files_exist {
74                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs:74",
                        "rustc_incremental::persist::load", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(74u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("reconcile_work_products: all files for {0:?} exist",
                                                    swp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("reconcile_work_products: all files for {:?} exist", swp);
75                prev_work_products.insert(swp.id, swp.work_product);
76            } else {
77                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs:77",
                        "rustc_incremental::persist::load", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(77u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("reconcile_work_products: some file for {0:?} does not exist",
                                                    swp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("reconcile_work_products: some file for {:?} does not exist", swp);
78                return LoadResult::DataOutOfDate;
79            }
80        }
81    }
82
83    let _prof_timer = sess.prof.generic_activity("incr_comp_load_dep_graph");
84
85    match file_format::open_incremental_file(sess, &path) {
86        Err(OpenFileError::NotFoundOrHeaderMismatch) => LoadResult::DataOutOfDate,
87        Err(OpenFileError::IoError { err }) => LoadResult::IoError { path: path.to_owned(), err },
88        Ok(OpenFile { mmap, start_pos }) => {
89            let Ok(mut decoder) = MemDecoder::new(&mmap, start_pos) else {
90                sess.dcx().emit_warn(diagnostics::CorruptFile { path: &path });
91                return LoadResult::DataOutOfDate;
92            };
93            let prev_commandline_args_hash = Hash64::decode(&mut decoder);
94
95            if prev_commandline_args_hash != expected_hash {
96                if sess.opts.unstable_opts.incremental_info {
97                    {
    ::std::io::_eprint(format_args!("[incremental] completely ignoring cache because of differing commandline arguments\n"));
};eprintln!(
98                        "[incremental] completely ignoring cache because of \
99                                    differing commandline arguments"
100                    );
101                }
102                // We can't reuse the cache, purge it.
103                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs:103",
                        "rustc_incremental::persist::load", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(103u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("load_dep_graph_new: differing commandline arg hashes")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("load_dep_graph_new: differing commandline arg hashes");
104
105                // No need to do any further work
106                return LoadResult::DataOutOfDate;
107            }
108
109            let prev_graph = SerializedDepGraph::decode(&mut decoder, &sess.prof);
110
111            LoadResult::Ok { prev_graph, prev_work_products }
112        }
113    }
114}
115
116/// Attempts to load the query result cache from disk
117///
118/// If we are not in incremental compilation mode, returns `None`.
119/// Otherwise, tries to load the query result cache from disk,
120/// creating an empty cache if it could not be loaded.
121pub fn load_query_result_cache(
122    sess: &Session,
123    incr_comp_session: Option<&IncrCompSession>,
124) -> Option<OnDiskCache> {
125    if sess.opts.incremental.is_none() {
126        return None;
127    }
128    let incr_comp_session = incr_comp_session.unwrap();
129
130    let _prof_timer = sess.prof.generic_activity("incr_comp_load_query_result_cache");
131
132    let Some(path) = old_query_cache_path(incr_comp_session) else {
133        return Some(OnDiskCache::new_empty());
134    };
135    match file_format::open_incremental_file(sess, &path) {
136        Ok(OpenFile { mmap, start_pos }) => {
137            let cache = OnDiskCache::new(sess, mmap, start_pos).unwrap_or_else(|()| {
138                sess.dcx().emit_warn(diagnostics::CorruptFile { path: &path });
139                OnDiskCache::new_empty()
140            });
141            Some(cache)
142        }
143        Err(OpenFileError::NotFoundOrHeaderMismatch | OpenFileError::IoError { .. }) => {
144            Some(OnDiskCache::new_empty())
145        }
146    }
147}
148
149/// Emits a fatal error if the assertion in `-Zassert-incr-state` doesn't match
150/// the outcome of trying to load previous-session state.
151fn maybe_assert_incr_state(sess: &Session, load_result: &LoadResult) {
152    // Return immediately if there's nothing to assert.
153    let Some(assertion) = sess.opts.unstable_opts.assert_incr_state else { return };
154
155    // Match exhaustively to make sure we don't miss any cases.
156    let loaded = match load_result {
157        LoadResult::Ok { .. } => true,
158        LoadResult::DataOutOfDate | LoadResult::IoError { .. } => false,
159    };
160
161    match assertion {
162        IncrementalStateAssertion::Loaded => {
163            if !loaded {
164                sess.dcx().emit_fatal(diagnostics::AssertLoaded);
165            }
166        }
167        IncrementalStateAssertion::NotLoaded => {
168            if loaded {
169                sess.dcx().emit_fatal(diagnostics::AssertNotLoaded)
170            }
171        }
172    }
173}
174
175/// Loads the previous session's dependency graph from disk if possible, and
176/// sets up streaming output for the current session's dep graph data into an
177/// incremental session directory.
178///
179/// In non-incremental mode, a dummy dep graph is returned immediately.
180pub fn setup_dep_graph(
181    sess: &Session,
182    crate_name: Symbol,
183    stable_crate_id: StableCrateId,
184) -> (DepGraph, Option<IncrCompSession>) {
185    if sess.opts.incremental.is_none() {
186        return (DepGraph::new_disabled(), None);
187    }
188
189    // `load_dep_graph` can only be called after `prepare_session_directory`.
190    let mut incr_comp_session = prepare_session_directory(sess, crate_name, stable_crate_id);
191    // Try to load the previous session's dep graph and work products.
192    let load_result = load_dep_graph(sess, &incr_comp_session);
193
194    sess.time("incr_comp_garbage_collect_session_directories", || {
195        if let Err(e) = garbage_collect_session_directories(sess, &incr_comp_session) {
196            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs:196",
                        "rustc_incremental::persist::load", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a75c3e0a67d3fa3d03982775f5bb0356e7b510/compiler/rustc_incremental/src/persist/load.rs"),
                        ::tracing_core::__macro_support::Option::Some(196u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_incremental::persist::load"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Error while trying to garbage collect incremental compilation cache directory: {0}",
                                                    e) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};warn!(
197                "Error while trying to garbage collect incremental compilation \
198                cache directory: {e}",
199            );
200        }
201    });
202
203    // Emit a fatal error if `-Zassert-incr-state` is present and unsatisfied.
204    maybe_assert_incr_state(sess, &load_result);
205
206    let (prev_graph, prev_work_products) = match load_result {
207        LoadResult::IoError { path, err } => {
208            sess.dcx().emit_warn(diagnostics::LoadDepGraph { path, err });
209            invalidate_old_session_dir(sess, &mut incr_comp_session);
210            Default::default()
211        }
212        LoadResult::DataOutOfDate => {
213            invalidate_old_session_dir(sess, &mut incr_comp_session);
214            Default::default()
215        }
216        LoadResult::Ok { prev_graph, prev_work_products } => (prev_graph, prev_work_products),
217    };
218
219    // Stream the dep-graph to an alternate file, to avoid overwriting anything in case of errors.
220    let path_buf = staging_dep_graph_path(&incr_comp_session);
221
222    let mut encoder = FileEncoder::new(&path_buf).unwrap_or_else(|err| {
223        // We're in incremental mode but couldn't set up streaming output of the dep graph.
224        // Exit immediately instead of continuing in an inconsistent and untested state.
225        sess.dcx().emit_fatal(diagnostics::CreateDepGraph { path: &path_buf, err })
226    });
227
228    file_format::write_file_header(&mut encoder, sess);
229
230    // First encode the commandline arguments hash
231    sess.opts.dep_tracking_hash(false).encode(&mut encoder);
232
233    (DepGraph::new(sess, prev_graph, prev_work_products, encoder), Some(incr_comp_session))
234}