]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_query_impl/src/plumbing.rs
correct span, add help message and add UI test when query depth overflows
[rust.git] / compiler / rustc_query_impl / src / plumbing.rs
1 //! The implementation of the query system itself. This defines the macros that
2 //! generate the actual methods on tcx which find and execute the provider,
3 //! manage the caches, and so forth.
4
5 use crate::keys::Key;
6 use crate::on_disk_cache::CacheDecoder;
7 use crate::{on_disk_cache, Queries};
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9 use rustc_data_structures::sync::{AtomicU64, Lock};
10 use rustc_errors::{Diagnostic, Handler};
11 use rustc_middle::dep_graph::{
12     self, DepKind, DepKindStruct, DepNode, DepNodeIndex, SerializedDepNodeIndex,
13 };
14 use rustc_middle::ty::tls::{self, ImplicitCtxt};
15 use rustc_middle::ty::{self, TyCtxt};
16 use rustc_query_system::dep_graph::{DepNodeParams, HasDepContext};
17 use rustc_query_system::ich::StableHashingContext;
18 use rustc_query_system::query::{
19     force_query, QueryConfig, QueryContext, QueryDescription, QueryJobId, QueryMap,
20     QuerySideEffects, QueryStackFrame,
21 };
22 use rustc_query_system::{LayoutOfDepth, QueryOverflow, Value};
23 use rustc_serialize::Decodable;
24 use rustc_session::Limit;
25 use rustc_span::def_id::LOCAL_CRATE;
26 use std::any::Any;
27 use std::num::NonZeroU64;
28 use thin_vec::ThinVec;
29
30 #[derive(Copy, Clone)]
31 pub struct QueryCtxt<'tcx> {
32     pub tcx: TyCtxt<'tcx>,
33     pub queries: &'tcx Queries<'tcx>,
34 }
35
36 impl<'tcx> std::ops::Deref for QueryCtxt<'tcx> {
37     type Target = TyCtxt<'tcx>;
38
39     #[inline]
40     fn deref(&self) -> &Self::Target {
41         &self.tcx
42     }
43 }
44
45 impl<'tcx> HasDepContext for QueryCtxt<'tcx> {
46     type DepKind = rustc_middle::dep_graph::DepKind;
47     type DepContext = TyCtxt<'tcx>;
48
49     #[inline]
50     fn dep_context(&self) -> &Self::DepContext {
51         &self.tcx
52     }
53 }
54
55 impl QueryContext for QueryCtxt<'_> {
56     fn next_job_id(&self) -> QueryJobId {
57         QueryJobId(
58             NonZeroU64::new(
59                 self.queries.jobs.fetch_add(1, rustc_data_structures::sync::Ordering::Relaxed),
60             )
61             .unwrap(),
62         )
63     }
64
65     fn current_query_job(&self) -> Option<QueryJobId> {
66         tls::with_related_context(**self, |icx| icx.query)
67     }
68
69     fn try_collect_active_jobs(&self) -> Option<QueryMap> {
70         self.queries.try_collect_active_jobs(**self)
71     }
72
73     // Interactions with on_disk_cache
74     fn load_side_effects(&self, prev_dep_node_index: SerializedDepNodeIndex) -> QuerySideEffects {
75         self.queries
76             .on_disk_cache
77             .as_ref()
78             .map(|c| c.load_side_effects(**self, prev_dep_node_index))
79             .unwrap_or_default()
80     }
81
82     fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
83         if let Some(c) = self.queries.on_disk_cache.as_ref() {
84             c.store_side_effects(dep_node_index, side_effects)
85         }
86     }
87
88     fn store_side_effects_for_anon_node(
89         &self,
90         dep_node_index: DepNodeIndex,
91         side_effects: QuerySideEffects,
92     ) {
93         if let Some(c) = self.queries.on_disk_cache.as_ref() {
94             c.store_side_effects_for_anon_node(dep_node_index, side_effects)
95         }
96     }
97
98     /// Executes a job by changing the `ImplicitCtxt` to point to the
99     /// new query job while it executes. It returns the diagnostics
100     /// captured during execution and the actual result.
101     #[inline(always)]
102     fn start_query<R>(
103         &self,
104         token: QueryJobId,
105         depth_limit: bool,
106         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
107         compute: impl FnOnce() -> R,
108     ) -> R {
109         // The `TyCtxt` stored in TLS has the same global interner lifetime
110         // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
111         // when accessing the `ImplicitCtxt`.
112         tls::with_related_context(**self, move |current_icx| {
113             if depth_limit && !self.recursion_limit().value_within_limit(current_icx.query_depth) {
114                 self.depth_limit_error(token);
115             }
116
117             // Update the `ImplicitCtxt` to point to our new query job.
118             let new_icx = ImplicitCtxt {
119                 tcx: **self,
120                 query: Some(token),
121                 diagnostics,
122                 query_depth: current_icx.query_depth + depth_limit as usize,
123                 task_deps: current_icx.task_deps,
124             };
125
126             // Use the `ImplicitCtxt` while we execute the query.
127             tls::enter_context(&new_icx, |_| {
128                 rustc_data_structures::stack::ensure_sufficient_stack(compute)
129             })
130         })
131     }
132
133     fn depth_limit_error(&self, job: QueryJobId) {
134         let mut span = None;
135         let mut layout_of_depth = None;
136         if let Some(map) = self.try_collect_active_jobs() {
137             if let Some((info, depth)) = job.try_find_layout_root(map) {
138                 span = Some(info.job.span);
139                 layout_of_depth = Some(LayoutOfDepth { desc: info.query.description, depth });
140             }
141         }
142
143         let suggested_limit = match self.recursion_limit() {
144             Limit(0) => Limit(2),
145             limit => limit * 2,
146         };
147
148         self.sess.emit_fatal(QueryOverflow {
149             span,
150             layout_of_depth,
151             suggested_limit,
152             crate_name: self.crate_name(LOCAL_CRATE),
153         });
154     }
155 }
156
157 impl<'tcx> QueryCtxt<'tcx> {
158     #[inline]
159     pub fn from_tcx(tcx: TyCtxt<'tcx>) -> Self {
160         let queries = tcx.queries.as_any();
161         let queries = unsafe {
162             let queries = std::mem::transmute::<&dyn Any, &dyn Any>(queries);
163             let queries = queries.downcast_ref().unwrap();
164             let queries = std::mem::transmute::<&Queries<'_>, &Queries<'_>>(queries);
165             queries
166         };
167         QueryCtxt { tcx, queries }
168     }
169
170     pub(crate) fn on_disk_cache(self) -> Option<&'tcx on_disk_cache::OnDiskCache<'tcx>> {
171         self.queries.on_disk_cache.as_ref()
172     }
173
174     pub(super) fn encode_query_results(
175         self,
176         encoder: &mut on_disk_cache::CacheEncoder<'_, 'tcx>,
177         query_result_index: &mut on_disk_cache::EncodedDepNodeIndex,
178     ) {
179         macro_rules! encode_queries {
180             ($($query:ident,)*) => {
181                 $(
182                     on_disk_cache::encode_query_results::<_, super::queries::$query<'_>>(
183                         self,
184                         encoder,
185                         query_result_index
186                     );
187                 )*
188             }
189         }
190
191         rustc_cached_queries!(encode_queries!);
192     }
193
194     pub fn try_print_query_stack(
195         self,
196         query: Option<QueryJobId>,
197         handler: &Handler,
198         num_frames: Option<usize>,
199     ) -> usize {
200         rustc_query_system::query::print_query_stack(self, query, handler, num_frames)
201     }
202 }
203
204 macro_rules! handle_cycle_error {
205     ([]) => {{
206         rustc_query_system::HandleCycleError::Error
207     }};
208     ([(fatal_cycle) $($rest:tt)*]) => {{
209         rustc_query_system::HandleCycleError::Fatal
210     }};
211     ([(cycle_delay_bug) $($rest:tt)*]) => {{
212         rustc_query_system::HandleCycleError::DelayBug
213     }};
214     ([$other:tt $($modifiers:tt)*]) => {
215         handle_cycle_error!([$($modifiers)*])
216     };
217 }
218
219 macro_rules! is_anon {
220     ([]) => {{
221         false
222     }};
223     ([(anon) $($rest:tt)*]) => {{
224         true
225     }};
226     ([$other:tt $($modifiers:tt)*]) => {
227         is_anon!([$($modifiers)*])
228     };
229 }
230
231 macro_rules! is_eval_always {
232     ([]) => {{
233         false
234     }};
235     ([(eval_always) $($rest:tt)*]) => {{
236         true
237     }};
238     ([$other:tt $($modifiers:tt)*]) => {
239         is_eval_always!([$($modifiers)*])
240     };
241 }
242
243 macro_rules! depth_limit {
244     ([]) => {{
245         false
246     }};
247     ([(depth_limit) $($rest:tt)*]) => {{
248         true
249     }};
250     ([$other:tt $($modifiers:tt)*]) => {
251         depth_limit!([$($modifiers)*])
252     };
253 }
254
255 macro_rules! hash_result {
256     ([]) => {{
257         Some(dep_graph::hash_result)
258     }};
259     ([(no_hash) $($rest:tt)*]) => {{
260         None
261     }};
262     ([$other:tt $($modifiers:tt)*]) => {
263         hash_result!([$($modifiers)*])
264     };
265 }
266
267 macro_rules! get_provider {
268     ([][$tcx:expr, $name:ident, $key:expr]) => {{
269         $tcx.queries.local_providers.$name
270     }};
271     ([(separate_provide_extern) $($rest:tt)*][$tcx:expr, $name:ident, $key:expr]) => {{
272         if $key.query_crate_is_local() {
273             $tcx.queries.local_providers.$name
274         } else {
275             $tcx.queries.extern_providers.$name
276         }
277     }};
278     ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => {
279         get_provider!([$($modifiers)*][$($args)*])
280     };
281 }
282
283 macro_rules! should_ever_cache_on_disk {
284     ([]) => {{
285         None
286     }};
287     ([(cache) $($rest:tt)*]) => {{
288         Some($crate::plumbing::try_load_from_disk::<Self::Value>)
289     }};
290     ([$other:tt $($modifiers:tt)*]) => {
291         should_ever_cache_on_disk!([$($modifiers)*])
292     };
293 }
294
295 pub(crate) fn create_query_frame<
296     'tcx,
297     K: Copy + Key + for<'a> HashStable<StableHashingContext<'a>>,
298 >(
299     tcx: QueryCtxt<'tcx>,
300     do_describe: fn(QueryCtxt<'tcx>, K) -> String,
301     key: K,
302     kind: DepKind,
303     name: &'static str,
304 ) -> QueryStackFrame {
305     // Disable visible paths printing for performance reasons.
306     // Showing visible path instead of any path is not that important in production.
307     let description = ty::print::with_no_visible_paths!(
308         // Force filename-line mode to avoid invoking `type_of` query.
309         ty::print::with_forced_impl_filename_line!(do_describe(tcx, key))
310     );
311     let description =
312         if tcx.sess.verbose() { format!("{} [{}]", description, name) } else { description };
313     let span = if kind == dep_graph::DepKind::def_span {
314         // The `def_span` query is used to calculate `default_span`,
315         // so exit to avoid infinite recursion.
316         None
317     } else {
318         Some(key.default_span(*tcx))
319     };
320     let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
321         // Try to avoid infinite recursion.
322         None
323     } else {
324         key.key_as_def_id()
325             .and_then(|def_id| def_id.as_local())
326             .and_then(|def_id| tcx.opt_def_kind(def_id))
327     };
328     let hash = || {
329         tcx.with_stable_hashing_context(|mut hcx| {
330             let mut hasher = StableHasher::new();
331             std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
332             key.hash_stable(&mut hcx, &mut hasher);
333             hasher.finish::<u64>()
334         })
335     };
336
337     QueryStackFrame::new(name, description, span, def_kind, hash)
338 }
339
340 fn try_load_from_on_disk_cache<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode)
341 where
342     Q: QueryDescription<QueryCtxt<'tcx>>,
343     Q::Key: DepNodeParams<TyCtxt<'tcx>>,
344 {
345     debug_assert!(tcx.dep_graph.is_green(&dep_node));
346
347     let key = Q::Key::recover(tcx, &dep_node).unwrap_or_else(|| {
348         panic!("Failed to recover key for {:?} with hash {}", dep_node, dep_node.hash)
349     });
350     if Q::cache_on_disk(tcx, &key) {
351         let _ = Q::execute_query(tcx, key);
352     }
353 }
354
355 pub(crate) fn try_load_from_disk<'tcx, V>(
356     tcx: QueryCtxt<'tcx>,
357     id: SerializedDepNodeIndex,
358 ) -> Option<V>
359 where
360     V: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
361 {
362     tcx.on_disk_cache().as_ref()?.try_load_query_result(*tcx, id)
363 }
364
365 fn force_from_dep_node<'tcx, Q>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> bool
366 where
367     Q: QueryDescription<QueryCtxt<'tcx>>,
368     Q::Key: DepNodeParams<TyCtxt<'tcx>>,
369     Q::Value: Value<TyCtxt<'tcx>>,
370 {
371     if let Some(key) = Q::Key::recover(tcx, &dep_node) {
372         #[cfg(debug_assertions)]
373         let _guard = tracing::span!(tracing::Level::TRACE, stringify!($name), ?key).entered();
374         let tcx = QueryCtxt::from_tcx(tcx);
375         force_query::<Q, _>(tcx, key, dep_node);
376         true
377     } else {
378         false
379     }
380 }
381
382 pub(crate) fn query_callback<'tcx, Q: QueryConfig>(
383     is_anon: bool,
384     is_eval_always: bool,
385 ) -> DepKindStruct<'tcx>
386 where
387     Q: QueryDescription<QueryCtxt<'tcx>>,
388     Q::Key: DepNodeParams<TyCtxt<'tcx>>,
389 {
390     let fingerprint_style = Q::Key::fingerprint_style();
391
392     if is_anon || !fingerprint_style.reconstructible() {
393         return DepKindStruct {
394             is_anon,
395             is_eval_always,
396             fingerprint_style,
397             force_from_dep_node: None,
398             try_load_from_on_disk_cache: None,
399         };
400     }
401
402     DepKindStruct {
403         is_anon,
404         is_eval_always,
405         fingerprint_style,
406         force_from_dep_node: Some(force_from_dep_node::<Q>),
407         try_load_from_on_disk_cache: Some(try_load_from_on_disk_cache::<Q>),
408     }
409 }
410
411 // NOTE: `$V` isn't used here, but we still need to match on it so it can be passed to other macros
412 // invoked by `rustc_query_append`.
413 macro_rules! define_queries {
414     (
415      $($(#[$attr:meta])*
416         [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
417         define_queries_struct! {
418             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
419         }
420
421         #[allow(nonstandard_style)]
422         mod queries {
423             use std::marker::PhantomData;
424
425             $(pub struct $name<'tcx> {
426                 data: PhantomData<&'tcx ()>
427             })*
428         }
429
430         $(impl<'tcx> QueryConfig for queries::$name<'tcx> {
431             type Key = query_keys::$name<'tcx>;
432             type Value = query_values::$name<'tcx>;
433             type Stored = query_stored::$name<'tcx>;
434             const NAME: &'static str = stringify!($name);
435         }
436
437         impl<'tcx> QueryDescription<QueryCtxt<'tcx>> for queries::$name<'tcx> {
438             rustc_query_description! { $name }
439
440             type Cache = query_storage::$name<'tcx>;
441
442             #[inline(always)]
443             fn query_state<'a>(tcx: QueryCtxt<'tcx>) -> &'a QueryState<Self::Key>
444                 where QueryCtxt<'tcx>: 'a
445             {
446                 &tcx.queries.$name
447             }
448
449             #[inline(always)]
450             fn query_cache<'a>(tcx: QueryCtxt<'tcx>) -> &'a Self::Cache
451                 where 'tcx:'a
452             {
453                 &tcx.query_caches.$name
454             }
455
456             #[inline]
457             fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
458                 QueryVTable<QueryCtxt<'tcx>, Self::Key, Self::Value>
459             {
460                 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
461                 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
462                 QueryVTable {
463                     anon: is_anon!([$($modifiers)*]),
464                     eval_always: is_eval_always!([$($modifiers)*]),
465                     depth_limit: depth_limit!([$($modifiers)*]),
466                     dep_kind: dep_graph::DepKind::$name,
467                     hash_result: hash_result!([$($modifiers)*]),
468                     handle_cycle_error: handle_cycle_error!([$($modifiers)*]),
469                     compute,
470                     try_load_from_disk: if cache_on_disk { should_ever_cache_on_disk!([$($modifiers)*]) } else { None },
471                 }
472             }
473
474             fn execute_query(tcx: TyCtxt<'tcx>, k: Self::Key) -> Self::Stored {
475                 tcx.$name(k)
476             }
477         })*
478
479         #[allow(nonstandard_style)]
480         mod query_callbacks {
481             use super::*;
482             use rustc_query_system::dep_graph::FingerprintStyle;
483
484             // We use this for most things when incr. comp. is turned off.
485             pub fn Null<'tcx>() -> DepKindStruct<'tcx> {
486                 DepKindStruct {
487                     is_anon: false,
488                     is_eval_always: false,
489                     fingerprint_style: FingerprintStyle::Unit,
490                     force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
491                     try_load_from_on_disk_cache: None,
492                 }
493             }
494
495             // We use this for the forever-red node.
496             pub fn Red<'tcx>() -> DepKindStruct<'tcx> {
497                 DepKindStruct {
498                     is_anon: false,
499                     is_eval_always: false,
500                     fingerprint_style: FingerprintStyle::Unit,
501                     force_from_dep_node: Some(|_, dep_node| bug!("force_from_dep_node: encountered {:?}", dep_node)),
502                     try_load_from_on_disk_cache: None,
503                 }
504             }
505
506             pub fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> {
507                 DepKindStruct {
508                     is_anon: true,
509                     is_eval_always: false,
510                     fingerprint_style: FingerprintStyle::Unit,
511                     force_from_dep_node: None,
512                     try_load_from_on_disk_cache: None,
513                 }
514             }
515
516             pub fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> {
517                 DepKindStruct {
518                     is_anon: false,
519                     is_eval_always: false,
520                     fingerprint_style: FingerprintStyle::Opaque,
521                     force_from_dep_node: None,
522                     try_load_from_on_disk_cache: None,
523                 }
524             }
525
526             pub fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> {
527                 DepKindStruct {
528                     is_anon: false,
529                     is_eval_always: false,
530                     fingerprint_style: FingerprintStyle::Opaque,
531                     force_from_dep_node: None,
532                     try_load_from_on_disk_cache: None,
533                 }
534             }
535
536             $(pub(crate) fn $name<'tcx>()-> DepKindStruct<'tcx> {
537                 $crate::plumbing::query_callback::<queries::$name<'tcx>>(
538                     is_anon!([$($modifiers)*]),
539                     is_eval_always!([$($modifiers)*]),
540                 )
541             })*
542         }
543
544         pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct<'tcx>] {
545             arena.alloc_from_iter(make_dep_kind_array!(query_callbacks))
546         }
547     }
548 }
549
550 use crate::{ExternProviders, OnDiskCache, Providers};
551
552 impl<'tcx> Queries<'tcx> {
553     pub fn new(
554         local_providers: Providers,
555         extern_providers: ExternProviders,
556         on_disk_cache: Option<OnDiskCache<'tcx>>,
557     ) -> Self {
558         Queries {
559             local_providers: Box::new(local_providers),
560             extern_providers: Box::new(extern_providers),
561             on_disk_cache,
562             jobs: AtomicU64::new(1),
563             ..Queries::default()
564         }
565     }
566 }
567
568 macro_rules! define_queries_struct {
569     (
570      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
571         #[derive(Default)]
572         pub struct Queries<'tcx> {
573             local_providers: Box<Providers>,
574             extern_providers: Box<ExternProviders>,
575
576             pub on_disk_cache: Option<OnDiskCache<'tcx>>,
577
578             jobs: AtomicU64,
579
580             $($(#[$attr])*  $name: QueryState<<queries::$name<'tcx> as QueryConfig>::Key>,)*
581         }
582
583         impl<'tcx> Queries<'tcx> {
584             pub(crate) fn try_collect_active_jobs(
585                 &'tcx self,
586                 tcx: TyCtxt<'tcx>,
587             ) -> Option<QueryMap> {
588                 let tcx = QueryCtxt { tcx, queries: self };
589                 let mut jobs = QueryMap::default();
590
591                 $(
592                     let make_query = |tcx, key| {
593                         let kind = dep_graph::DepKind::$name;
594                         let name = stringify!($name);
595                         $crate::plumbing::create_query_frame(tcx, queries::$name::describe, key, kind, name)
596                     };
597                     self.$name.try_collect_active_jobs(
598                         tcx,
599                         make_query,
600                         &mut jobs,
601                     )?;
602                 )*
603
604                 Some(jobs)
605             }
606         }
607
608         impl<'tcx> QueryEngine<'tcx> for Queries<'tcx> {
609             fn as_any(&'tcx self) -> &'tcx dyn std::any::Any {
610                 let this = unsafe { std::mem::transmute::<&Queries<'_>, &Queries<'_>>(self) };
611                 this as _
612             }
613
614             fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool {
615                 let qcx = QueryCtxt { tcx, queries: self };
616                 tcx.dep_graph.try_mark_green(qcx, dep_node).is_some()
617             }
618
619             $($(#[$attr])*
620             #[inline(always)]
621             #[tracing::instrument(level = "trace", skip(self, tcx), ret)]
622             fn $name(
623                 &'tcx self,
624                 tcx: TyCtxt<'tcx>,
625                 span: Span,
626                 key: <queries::$name<'tcx> as QueryConfig>::Key,
627                 mode: QueryMode,
628             ) -> Option<query_stored::$name<'tcx>> {
629                 let qcx = QueryCtxt { tcx, queries: self };
630                 get_query::<queries::$name<'tcx>, _>(qcx, span, key, mode)
631             })*
632         }
633     };
634 }