Skip to main content

rustc_middle/
ich.rs

1use std::hash::Hash;
2
3use rustc_crate_store::Untracked;
4use rustc_data_structures::fingerprint::Fingerprint;
5use rustc_data_structures::stable_hash::{
6    RawDefId, RawSpan, StableHash, StableHashControls, StableHashCtxt, StableHasher,
7};
8use rustc_data_structures::sync::AppendOnlyIndexVec;
9use rustc_hir::def_id::{DefId, LocalDefId};
10use rustc_session::Session;
11use rustc_span::source_map::SourceMap;
12use rustc_span::{BytePos, CachingSourceMapView, DUMMY_SP, Pos, Span, SpanData};
13
14// Very often, we are hashing something that does not need the `CachingSourceMapView`, so we
15// initialize it lazily.
16enum CachingSourceMap<'a> {
17    Unused(&'a SourceMap),
18    InUse(CachingSourceMapView<'a>),
19}
20
21/// This is the context state available during incr. comp. hashing. It contains
22/// enough information to transform `DefId`s and `HirId`s into stable `DefPath`s (i.e.,
23/// a reference to the `TyCtxt`) and it holds a few caches for speeding up various
24/// things (e.g., each `DefId`/`DefPath` is only hashed once).
25pub struct StableHashState<'a> {
26    untracked: &'a Untracked,
27    // The value of `-Z incremental-ignore-spans`.
28    // This field should only be used by `unstable_opts_incremental_ignore_span`
29    incremental_ignore_spans: bool,
30    caching_source_map: CachingSourceMap<'a>,
31    stable_hash_controls: StableHashControls,
32    source_span_cache: SourceSpanCache,
33}
34
35impl<'a> StableHashState<'a> {
36    #[inline]
37    pub fn new(sess: &'a Session, untracked: &'a Untracked) -> Self {
38        let hash_spans_initial = !sess.opts.unstable_opts.incremental_ignore_spans;
39
40        StableHashState {
41            untracked,
42            incremental_ignore_spans: sess.opts.unstable_opts.incremental_ignore_spans,
43            caching_source_map: CachingSourceMap::Unused(sess.source_map()),
44            stable_hash_controls: StableHashControls { hash_spans: hash_spans_initial },
45            source_span_cache: SourceSpanCache::default(),
46        }
47    }
48
49    #[inline]
50    pub fn while_hashing_spans<F: FnOnce(&mut Self)>(&mut self, hash_spans: bool, f: F) {
51        let prev_hash_spans = self.stable_hash_controls.hash_spans;
52        self.stable_hash_controls.hash_spans = hash_spans;
53        f(self);
54        self.stable_hash_controls.hash_spans = prev_hash_spans;
55    }
56
57    #[inline]
58    fn source_map(&mut self) -> &mut CachingSourceMapView<'a> {
59        match self.caching_source_map {
60            CachingSourceMap::InUse(ref mut sm) => sm,
61            CachingSourceMap::Unused(sm) => {
62                self.caching_source_map = CachingSourceMap::InUse(CachingSourceMapView::new(sm));
63                self.source_map() // this recursive call will hit the `InUse` case
64            }
65        }
66    }
67
68    #[inline]
69    pub fn stable_hash_controls(&self) -> StableHashControls {
70        self.stable_hash_controls
71    }
72}
73
74impl<'a> StableHashCtxt for StableHashState<'a> {
75    /// Hashes a span in a stable way. We can't directly hash the span's `BytePos` fields (that
76    /// would be similar to hashing pointers, since those are just offsets into the `SourceMap`).
77    /// Instead, we hash the (file name, line, column) triple, which stays the same even if the
78    /// containing `SourceFile` has moved within the `SourceMap`.
79    ///
80    /// Also note that we are hashing byte offsets for the column, not unicode codepoint offsets.
81    /// For the purpose of the hash that's sufficient. Also, hashing filenames is expensive so we
82    /// avoid doing it twice when the span starts and ends in the same file, which is almost always
83    /// the case.
84    ///
85    /// IMPORTANT: changes to this method should be reflected in implementations of `SpanEncoder`.
86    #[inline]
87    fn stable_hash_span(&mut self, raw_span: RawSpan, hasher: &mut StableHasher) {
88        const TAG_VALID_SPAN: u8 = 0;
89        const TAG_INVALID_SPAN: u8 = 1;
90        const TAG_RELATIVE_SPAN: u8 = 2;
91
92        #[inline]
93        fn pack_span_location(
94            line_lo: usize,
95            col_lo: BytePos,
96            line_hi: usize,
97            col_hi: BytePos,
98        ) -> u64 {
99            let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
100            let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
101            let col_hi_trunc = ((col_hi.0 as u64) & 0xFF) << 32;
102            let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
103            col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc
104        }
105
106        if !self.stable_hash_controls().hash_spans {
107            return;
108        }
109
110        let span = Span::from_raw_span(raw_span);
111        let span = span.data_untracked();
112        span.ctxt.stable_hash(self, hasher);
113        span.parent.stable_hash(self, hasher);
114
115        if span.is_dummy() {
116            Hash::hash(&TAG_INVALID_SPAN, hasher);
117            return;
118        }
119
120        let parent = span
121            .parent
122            .map(|parent| self.source_span_cache.lookup(parent, &self.untracked.source_span));
123        if let Some(parent) = parent
124            && parent.contains(span)
125        {
126            // This span is enclosed in a definition: only hash the relative position. This catches
127            // a subset of the cases from the `file.contains(parent.lo)`. But we can do this check
128            // cheaply without the expensive `span_data_to_lines_and_cols` query.
129            Hash::hash(&TAG_RELATIVE_SPAN, hasher);
130            (span.lo - parent.lo).to_u32().stable_hash(self, hasher);
131            (span.hi - parent.lo).to_u32().stable_hash(self, hasher);
132            return;
133        }
134
135        // If this is not an empty or invalid span, we want to hash the last position that belongs
136        // to it, as opposed to hashing the first position past it.
137        let Some((file, line_lo, col_lo, line_hi, col_hi)) =
138            self.source_map().span_data_to_lines_and_cols(&span)
139        else {
140            Hash::hash(&TAG_INVALID_SPAN, hasher);
141            return;
142        };
143
144        if let Some(parent) = parent
145            && file.contains(parent.lo)
146        {
147            // This span is relative to another span in the same file,
148            // only hash the relative position.
149            Hash::hash(&TAG_RELATIVE_SPAN, hasher);
150            Hash::hash(&(span.lo.0.wrapping_sub(parent.lo.0)), hasher);
151            Hash::hash(&(span.hi.0.wrapping_sub(parent.lo.0)), hasher);
152            return;
153        }
154
155        Hash::hash(&TAG_VALID_SPAN, hasher);
156        Hash::hash(&file.stable_id, hasher);
157
158        // Hash both the length and the end location (line/column) of a span. If we hash only the
159        // length, for example, then two otherwise equal spans with different end locations will
160        // have the same hash. This can cause a problem during incremental compilation wherein a
161        // previous result for a query that depends on the end location of a span will be
162        // incorrectly reused when the end location of the span it depends on has changed (see
163        // issue #74890). A similar analysis applies if some query depends specifically on the
164        // length of the span, but we only hash the end location. So hash both.
165
166        let col_line = pack_span_location(line_lo, col_lo, line_hi, col_hi);
167        let len = (span.hi - span.lo).0;
168        Hash::hash(&col_line, hasher);
169        Hash::hash(&len, hasher);
170    }
171
172    #[inline]
173    fn def_path_hash(&self, raw_def_id: RawDefId) -> Fingerprint {
174        let def_id = DefId::from_raw_def_id(raw_def_id);
175        if let Some(def_id) = def_id.as_local() {
176            self.untracked.definitions.read().def_path_hash(def_id)
177        } else {
178            self.untracked.cstore.read().def_path_hash(def_id)
179        }
180        .0
181    }
182
183    /// Assert that the provided `StableHashCtxt` is configured with the default
184    /// `StableHashControls`. We should always have bailed out before getting to here with a
185    /// non-default mode. With this check in place, we can avoid the need to maintain separate
186    /// versions of `ExpnData` hashes for each permutation of `StableHashControls` settings.
187    #[inline]
188    fn assert_default_stable_hash_controls(&self, msg: &str) {
189        let stable_hash_controls = self.stable_hash_controls;
190        let StableHashControls { hash_spans } = stable_hash_controls;
191
192        // Note that we require that `hash_spans` be the inverse of the global `-Z
193        // incremental-ignore-spans` option. Normally, this option is disabled, in which case
194        // `hash_spans` must be true.
195        //
196        // Span hashing can also be disabled without `-Z incremental-ignore-spans`. This is the
197        // case for instance when building a hash for name mangling. Such configuration must not be
198        // used for metadata.
199        {
    match (&hash_spans, &!self.incremental_ignore_spans) {
        (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!("Attempted hashing of {0} with non-default StableHashControls: {1:?}",
                            msg, stable_hash_controls)));
            }
        }
    }
};assert_eq!(
200            hash_spans, !self.incremental_ignore_spans,
201            "Attempted hashing of {msg} with non-default StableHashControls: {stable_hash_controls:?}"
202        );
203    }
204
205    #[inline]
206    fn stable_hash_controls(&self) -> StableHashControls {
207        self.stable_hash_controls
208    }
209}
210
211/// A single-entry cache for a `SpanData`, to optimize a particular scenario: when iterating
212/// through child spans (e.g. during encoding/decoding/hashing), many of those spans will have the
213/// same parent span. In the case where that parent span is interned (e.g. the parent is a const
214/// literal item exceeding MAX_LEN bytes of source code), this cache avoids having to fetch the
215/// parent's `SpanData` from the interner (which involves TLS, locking, etc.) over and over. A
216/// single entry is enough for an extremely high hit rate.
217#[derive(#[automatically_derived]
impl ::core::default::Default for SourceSpanCache {
    #[inline]
    fn default() -> Self {
        SourceSpanCache(::core::default::Default::default())
    }
}Default)]
218pub(crate) struct SourceSpanCache(Option<(LocalDefId, SpanData)>);
219
220impl SourceSpanCache {
221    #[inline]
222    pub(crate) fn lookup(
223        &mut self,
224        def_id: LocalDefId,
225        source_span: &AppendOnlyIndexVec<LocalDefId, Span>,
226    ) -> SpanData {
227        if let Some(cache) = self.0
228            && cache.0 == def_id
229        {
230            cache.1
231        } else {
232            let span_data = source_span.get(def_id).unwrap_or(DUMMY_SP).data_untracked();
233            self.0 = Some((def_id, span_data));
234            span_data
235        }
236    }
237}