-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
plumbing.rs
1280 lines (1129 loc) · 50.9 KB
/
plumbing.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The implementation of the query system itself. Defines the macros
//! that generate the actual methods on tcx which find and execute the
//! provider, manage the caches, and so forth.
use dep_graph::{DepNodeIndex, DepNode, DepKind, DepNodeColor};
use errors::DiagnosticBuilder;
use errors::Level;
use errors::Diagnostic;
use errors::FatalError;
use ty::tls;
use ty::{TyCtxt};
use ty::query::Query;
use ty::query::config::{QueryConfig, QueryDescription};
use ty::query::job::{QueryJob, QueryResult, QueryInfo};
use ty::item_path;
use util::common::{profq_msg, ProfileQueriesMsg, QueryMsg};
use rustc_data_structures::fx::{FxHashMap};
use rustc_data_structures::sync::{Lrc, Lock};
use std::mem;
use std::ptr;
use std::collections::hash_map::Entry;
use syntax_pos::Span;
use syntax::codemap::DUMMY_SP;
pub struct QueryCache<'tcx, D: QueryConfig<'tcx> + ?Sized> {
pub(super) results: FxHashMap<D::Key, QueryValue<D::Value>>,
pub(super) active: FxHashMap<D::Key, QueryResult<'tcx>>,
}
pub(super) struct QueryValue<T> {
pub(super) value: T,
pub(super) index: DepNodeIndex,
}
impl<T> QueryValue<T> {
pub(super) fn new(value: T,
dep_node_index: DepNodeIndex)
-> QueryValue<T> {
QueryValue {
value,
index: dep_node_index,
}
}
}
impl<'tcx, M: QueryConfig<'tcx>> QueryCache<'tcx, M> {
pub(super) fn new() -> QueryCache<'tcx, M> {
QueryCache {
results: FxHashMap(),
active: FxHashMap(),
}
}
}
// If enabled, send a message to the profile-queries thread
macro_rules! profq_msg {
($tcx:expr, $msg:expr) => {
if cfg!(debug_assertions) {
if $tcx.sess.profile_queries() {
profq_msg($tcx.sess, $msg)
}
}
}
}
// If enabled, format a key using its debug string, which can be
// expensive to compute (in terms of time).
macro_rules! profq_query_msg {
($query:expr, $tcx:expr, $key:expr) => {{
let msg = if cfg!(debug_assertions) {
if $tcx.sess.profile_queries_and_keys() {
Some(format!("{:?}", $key))
} else { None }
} else { None };
QueryMsg {
query: $query,
msg,
}
}}
}
/// A type representing the responsibility to execute the job in the `job` field.
/// This will poison the relevant query if dropped.
pub(super) struct JobOwner<'a, 'tcx: 'a, Q: QueryDescription<'tcx> + 'a> {
cache: &'a Lock<QueryCache<'tcx, Q>>,
key: Q::Key,
job: Lrc<QueryJob<'tcx>>,
}
impl<'a, 'tcx, Q: QueryDescription<'tcx>> JobOwner<'a, 'tcx, Q> {
/// Either gets a JobOwner corresponding the the query, allowing us to
/// start executing the query, or it returns with the result of the query.
/// If the query is executing elsewhere, this will wait for it.
/// If the query panicked, this will silently panic.
///
/// This function is inlined because that results in a noticeable speedup
/// for some compile-time benchmarks.
#[inline(always)]
pub(super) fn try_get(
tcx: TyCtxt<'a, 'tcx, '_>,
span: Span,
key: &Q::Key,
) -> TryGetJob<'a, 'tcx, Q> {
let cache = Q::query_cache(tcx);
loop {
let mut lock = cache.borrow_mut();
if let Some(value) = lock.results.get(key) {
profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
let result = Ok((value.value.clone(), value.index));
return TryGetJob::JobCompleted(result);
}
let job = match lock.active.entry((*key).clone()) {
Entry::Occupied(entry) => {
match *entry.get() {
QueryResult::Started(ref job) => job.clone(),
QueryResult::Poisoned => FatalError.raise(),
}
}
Entry::Vacant(entry) => {
// No job entry for this query. Return a new one to be started later
return tls::with_related_context(tcx, |icx| {
let info = QueryInfo {
span,
query: Q::query(key.clone()),
};
let job = Lrc::new(QueryJob::new(info, icx.query.clone()));
let owner = JobOwner {
cache,
job: job.clone(),
key: (*key).clone(),
};
entry.insert(QueryResult::Started(job));
TryGetJob::NotYetStarted(owner)
})
}
};
mem::drop(lock);
if let Err(cycle) = job.await(tcx, span) {
return TryGetJob::JobCompleted(Err(cycle));
}
}
}
/// Completes the query by updating the query cache with the `result`,
/// signals the waiter and forgets the JobOwner, so it won't poison the query
pub(super) fn complete(self, result: &Q::Value, dep_node_index: DepNodeIndex) {
// We can move out of `self` here because we `mem::forget` it below
let key = unsafe { ptr::read(&self.key) };
let job = unsafe { ptr::read(&self.job) };
let cache = self.cache;
// Forget ourself so our destructor won't poison the query
mem::forget(self);
let value = QueryValue::new(result.clone(), dep_node_index);
{
let mut lock = cache.borrow_mut();
lock.active.remove(&key);
lock.results.insert(key, value);
}
job.signal_complete();
}
/// Executes a job by changing the ImplicitCtxt to point to the
/// new query job while it executes. It returns the diagnostics
/// captured during execution and the actual result.
pub(super) fn start<'lcx, F, R>(
&self,
tcx: TyCtxt<'_, 'tcx, 'lcx>,
compute: F)
-> (R, Vec<Diagnostic>)
where
F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'lcx>) -> R
{
// The TyCtxt stored in TLS has the same global interner lifetime
// as `tcx`, so we use `with_related_context` to relate the 'gcx lifetimes
// when accessing the ImplicitCtxt
let r = tls::with_related_context(tcx, move |current_icx| {
// Update the ImplicitCtxt to point to our new query job
let new_icx = tls::ImplicitCtxt {
tcx,
query: Some(self.job.clone()),
layout_depth: current_icx.layout_depth,
task: current_icx.task,
};
// Use the ImplicitCtxt while we execute the query
tls::enter_context(&new_icx, |_| {
compute(tcx)
})
});
// Extract the diagnostic from the job
let diagnostics = mem::replace(&mut *self.job.diagnostics.lock(), Vec::new());
(r, diagnostics)
}
}
impl<'a, 'tcx, Q: QueryDescription<'tcx>> Drop for JobOwner<'a, 'tcx, Q> {
fn drop(&mut self) {
// Poison the query so jobs waiting on it panic
self.cache.borrow_mut().active.insert(self.key.clone(), QueryResult::Poisoned);
// Also signal the completion of the job, so waiters
// will continue execution
self.job.signal_complete();
}
}
#[derive(Clone)]
pub struct CycleError<'tcx> {
/// The query and related span which uses the cycle
pub(super) usage: Option<(Span, Query<'tcx>)>,
pub(super) cycle: Vec<QueryInfo<'tcx>>,
}
/// The result of `try_get_lock`
pub(super) enum TryGetJob<'a, 'tcx: 'a, D: QueryDescription<'tcx> + 'a> {
/// The query is not yet started. Contains a guard to the cache eventually used to start it.
NotYetStarted(JobOwner<'a, 'tcx, D>),
/// The query was already completed.
/// Returns the result of the query and its dep node index
/// if it succeeded or a cycle error if it failed
JobCompleted(Result<(D::Value, DepNodeIndex), CycleError<'tcx>>),
}
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub(super) fn report_cycle(self, CycleError { usage, cycle: stack }: CycleError<'gcx>)
-> DiagnosticBuilder<'a>
{
assert!(!stack.is_empty());
let fix_span = |span: Span, query: &Query<'gcx>| {
self.sess.codemap().def_span(query.default_span(self, span))
};
// Disable naming impls with types in this path, since that
// sometimes cycles itself, leading to extra cycle errors.
// (And cycle errors around impls tend to occur during the
// collect/coherence phases anyhow.)
item_path::with_forced_impl_filename_line(|| {
let span = fix_span(stack[1 % stack.len()].span, &stack[0].query);
let mut err = struct_span_err!(self.sess,
span,
E0391,
"cycle detected when {}",
stack[0].query.describe(self));
for i in 1..stack.len() {
let query = &stack[i].query;
let span = fix_span(stack[(i + 1) % stack.len()].span, query);
err.span_note(span, &format!("...which requires {}...", query.describe(self)));
}
err.note(&format!("...which again requires {}, completing the cycle",
stack[0].query.describe(self)));
if let Some((span, query)) = usage {
err.span_note(fix_span(span, &query),
&format!("cycle used when {}", query.describe(self)));
}
return err
})
}
pub fn try_print_query_stack() {
eprintln!("query stack during panic:");
tls::with_context_opt(|icx| {
if let Some(icx) = icx {
let mut current_query = icx.query.clone();
let mut i = 0;
while let Some(query) = current_query {
let mut db = DiagnosticBuilder::new(icx.tcx.sess.diagnostic(),
Level::FailureNote,
&format!("#{} [{}] {}",
i,
query.info.query.name(),
query.info.query.describe(icx.tcx)));
db.set_span(icx.tcx.sess.codemap().def_span(query.info.span));
icx.tcx.sess.diagnostic().force_print_db(db);
current_query = query.parent.clone();
i += 1;
}
}
});
eprintln!("end of query stack");
}
/// Try to read a node index for the node dep_node.
/// A node will have an index, when it's already been marked green, or when we can mark it
/// green. This function will mark the current task as a reader of the specified node, when
/// the a node index can be found for that node.
pub(super) fn try_mark_green_and_read(self, dep_node: &DepNode) -> Option<DepNodeIndex> {
match self.dep_graph.node_color(dep_node) {
Some(DepNodeColor::Green(dep_node_index)) => {
self.dep_graph.read_index(dep_node_index);
Some(dep_node_index)
}
Some(DepNodeColor::Red) => {
None
}
None => {
// try_mark_green (called below) will panic when full incremental
// compilation is disabled. If that's the case, we can't try to mark nodes
// as green anyway, so we can safely return None here.
if !self.dep_graph.is_fully_enabled() {
return None;
}
match self.dep_graph.try_mark_green(self.global_tcx(), &dep_node) {
Some(dep_node_index) => {
debug_assert!(self.dep_graph.is_green(&dep_node));
self.dep_graph.read_index(dep_node_index);
Some(dep_node_index)
}
None => {
None
}
}
}
}
}
fn try_get_with<Q: QueryDescription<'gcx>>(
self,
span: Span,
key: Q::Key)
-> Result<Q::Value, CycleError<'gcx>>
{
debug!("ty::queries::{}::try_get_with(key={:?}, span={:?})",
Q::NAME,
key,
span);
profq_msg!(self,
ProfileQueriesMsg::QueryBegin(
span.data(),
profq_query_msg!(Q::NAME, self, key),
)
);
let job = match JobOwner::try_get(self, span, &key) {
TryGetJob::NotYetStarted(job) => job,
TryGetJob::JobCompleted(result) => {
return result.map(|(v, index)| {
self.dep_graph.read_index(index);
v
})
}
};
// Fast path for when incr. comp. is off. `to_dep_node` is
// expensive for some DepKinds.
if !self.dep_graph.is_fully_enabled() {
let null_dep_node = DepNode::new_no_params(::dep_graph::DepKind::Null);
return self.force_query_with_job::<Q>(key, job, null_dep_node).map(|(v, _)| v);
}
let dep_node = Q::to_dep_node(self, &key);
if dep_node.kind.is_anon() {
profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
let res = job.start(self, |tcx| {
tcx.dep_graph.with_anon_task(dep_node.kind, || {
Q::compute(tcx.global_tcx(), key)
})
});
profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
let ((result, dep_node_index), diagnostics) = res;
self.dep_graph.read_index(dep_node_index);
self.queries.on_disk_cache
.store_diagnostics_for_anon_node(dep_node_index, diagnostics);
job.complete(&result, dep_node_index);
return Ok(result);
}
if !dep_node.kind.is_input() {
if let Some(dep_node_index) = self.try_mark_green_and_read(&dep_node) {
profq_msg!(self, ProfileQueriesMsg::CacheHit);
return self.load_from_disk_and_cache_in_memory::<Q>(key,
job,
dep_node_index,
&dep_node)
}
}
match self.force_query_with_job::<Q>(key, job, dep_node) {
Ok((result, dep_node_index)) => {
self.dep_graph.read_index(dep_node_index);
Ok(result)
}
Err(e) => Err(e)
}
}
fn load_from_disk_and_cache_in_memory<Q: QueryDescription<'gcx>>(
self,
key: Q::Key,
job: JobOwner<'a, 'gcx, Q>,
dep_node_index: DepNodeIndex,
dep_node: &DepNode
) -> Result<Q::Value, CycleError<'gcx>>
{
// Note this function can be called concurrently from the same query
// We must ensure that this is handled correctly
debug_assert!(self.dep_graph.is_green(dep_node));
// First we try to load the result from the on-disk cache
let result = if Q::cache_on_disk(key.clone()) &&
self.sess.opts.debugging_opts.incremental_queries {
let prev_dep_node_index =
self.dep_graph.prev_dep_node_index_of(dep_node);
let result = Q::try_load_from_disk(self.global_tcx(),
prev_dep_node_index);
// We always expect to find a cached result for things that
// can be forced from DepNode.
debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
result.is_some(),
"Missing on-disk cache entry for {:?}",
dep_node);
result
} else {
// Some things are never cached on disk.
None
};
let result = if let Some(result) = result {
result
} else {
// We could not load a result from the on-disk cache, so
// recompute.
// The diagnostics for this query have already been
// promoted to the current session during
// try_mark_green(), so we can ignore them here.
let (result, _) = job.start(self, |tcx| {
// The dep-graph for this computation is already in
// place
tcx.dep_graph.with_ignore(|| {
Q::compute(tcx, key)
})
});
result
};
// If -Zincremental-verify-ich is specified, re-hash results from
// the cache and make sure that they have the expected fingerprint.
if self.sess.opts.debugging_opts.incremental_verify_ich {
use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
use ich::Fingerprint;
assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
self.dep_graph.prev_fingerprint_of(dep_node),
"Fingerprint for green query instance not loaded \
from cache: {:?}", dep_node);
debug!("BEGIN verify_ich({:?})", dep_node);
let mut hcx = self.create_stable_hashing_context();
let mut hasher = StableHasher::new();
result.hash_stable(&mut hcx, &mut hasher);
let new_hash: Fingerprint = hasher.finish();
debug!("END verify_ich({:?})", dep_node);
let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
assert!(new_hash == old_hash, "Found unstable fingerprints \
for {:?}", dep_node);
}
if self.sess.opts.debugging_opts.query_dep_graph {
self.dep_graph.mark_loaded_from_cache(dep_node_index, true);
}
job.complete(&result, dep_node_index);
Ok(result)
}
fn force_query_with_job<Q: QueryDescription<'gcx>>(
self,
key: Q::Key,
job: JobOwner<'_, 'gcx, Q>,
dep_node: DepNode)
-> Result<(Q::Value, DepNodeIndex), CycleError<'gcx>> {
// If the following assertion triggers, it can have two reasons:
// 1. Something is wrong with DepNode creation, either here or
// in DepGraph::try_mark_green()
// 2. Two distinct query keys get mapped to the same DepNode
// (see for example #48923)
assert!(!self.dep_graph.dep_node_exists(&dep_node),
"Forcing query with already existing DepNode.\n\
- query-key: {:?}\n\
- dep-node: {:?}",
key, dep_node);
profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
let res = job.start(self, |tcx| {
if dep_node.kind.is_eval_always() {
tcx.dep_graph.with_eval_always_task(dep_node,
tcx,
key,
Q::compute)
} else {
tcx.dep_graph.with_task(dep_node,
tcx,
key,
Q::compute)
}
});
profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
let ((result, dep_node_index), diagnostics) = res;
if self.sess.opts.debugging_opts.query_dep_graph {
self.dep_graph.mark_loaded_from_cache(dep_node_index, false);
}
if dep_node.kind != ::dep_graph::DepKind::Null {
self.queries.on_disk_cache
.store_diagnostics(dep_node_index, diagnostics);
}
job.complete(&result, dep_node_index);
Ok((result, dep_node_index))
}
/// Ensure that either this query has all green inputs or been executed.
/// Executing query::ensure(D) is considered a read of the dep-node D.
///
/// This function is particularly useful when executing passes for their
/// side-effects -- e.g., in order to report errors for erroneous programs.
///
/// Note: The optimization is only available during incr. comp.
pub(super) fn ensure_query<Q: QueryDescription<'gcx>>(self, key: Q::Key) -> () {
let dep_node = Q::to_dep_node(self, &key);
// Ensuring an "input" or anonymous query makes no sense
assert!(!dep_node.kind.is_anon());
assert!(!dep_node.kind.is_input());
if self.try_mark_green_and_read(&dep_node).is_none() {
// A None return from `try_mark_green_and_read` means that this is either
// a new dep node or that the dep node has already been marked red.
// Either way, we can't call `dep_graph.read()` as we don't have the
// DepNodeIndex. We must invoke the query itself. The performance cost
// this introduces should be negligible as we'll immediately hit the
// in-memory cache, or another query down the line will.
let _ = self.get_query::<Q>(DUMMY_SP, key);
}
}
#[allow(dead_code)]
fn force_query<Q: QueryDescription<'gcx>>(
self,
key: Q::Key,
span: Span,
dep_node: DepNode
) -> Result<(Q::Value, DepNodeIndex), CycleError<'gcx>> {
// We may be concurrently trying both execute and force a query
// Ensure that only one of them runs the query
let job = match JobOwner::try_get(self, span, &key) {
TryGetJob::NotYetStarted(job) => job,
TryGetJob::JobCompleted(result) => return result,
};
self.force_query_with_job::<Q>(key, job, dep_node)
}
pub(super) fn try_get_query<Q: QueryDescription<'gcx>>(
self,
span: Span,
key: Q::Key,
) -> Result<Q::Value, DiagnosticBuilder<'a>> {
match self.try_get_with::<Q>(span, key) {
Ok(e) => Ok(e),
Err(e) => Err(self.report_cycle(e)),
}
}
pub(super) fn get_query<Q: QueryDescription<'gcx>>(
self,
span: Span,
key: Q::Key,
) -> Q::Value {
self.try_get_query::<Q>(span, key).unwrap_or_else(|mut e| {
e.emit();
Q::handle_cycle_error(self)
})
}
}
macro_rules! handle_cycle_error {
([][$this: expr]) => {{
Value::from_cycle_error($this.global_tcx())
}};
([fatal_cycle$(, $modifiers:ident)*][$this:expr]) => {{
$this.sess.abort_if_errors();
unreachable!();
}};
([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
handle_cycle_error!([$($modifiers),*][$($args)*])
};
}
macro_rules! define_queries {
(<$tcx:tt>
$($(#[$attr:meta])*
[$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => {
use std::mem;
#[cfg(parallel_queries)]
use ty::query::job::QueryResult;
use rustc_data_structures::sync::Lock;
use {
rustc_data_structures::stable_hasher::HashStable,
rustc_data_structures::stable_hasher::StableHasherResult,
rustc_data_structures::stable_hasher::StableHasher,
ich::StableHashingContext
};
define_queries_struct! {
tcx: $tcx,
input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
}
impl<$tcx> Queries<$tcx> {
pub fn new(
providers: IndexVec<CrateNum, Providers<$tcx>>,
on_disk_cache: OnDiskCache<'tcx>,
) -> Self {
Queries {
providers,
on_disk_cache,
$($name: Lock::new(QueryCache::new())),*
}
}
#[cfg(parallel_queries)]
pub fn collect_active_jobs(&self) -> Vec<Lrc<QueryJob<$tcx>>> {
let mut jobs = Vec::new();
// We use try_lock here since we are only called from the
// deadlock handler, and this shouldn't be locked
$(for v in self.$name.try_lock().unwrap().active.values() {
match *v {
QueryResult::Started(ref job) => jobs.push(job.clone()),
_ => (),
}
})*
return jobs;
}
}
#[allow(bad_style)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Query<$tcx> {
$($(#[$attr])* $name($K)),*
}
impl<$tcx> Query<$tcx> {
pub fn name(&self) -> &'static str {
match *self {
$(Query::$name(_) => stringify!($name),)*
}
}
pub fn describe(&self, tcx: TyCtxt) -> String {
let (r, name) = match *self {
$(Query::$name(key) => {
(queries::$name::describe(tcx, key), stringify!($name))
})*
};
if tcx.sess.verbose() {
format!("{} [{}]", r, name)
} else {
r
}
}
// FIXME(eddyb) Get more valid Span's on queries.
pub fn default_span(&self, tcx: TyCtxt<'_, $tcx, '_>, span: Span) -> Span {
if span != DUMMY_SP {
return span;
}
// The def_span query is used to calculate default_span,
// so exit to avoid infinite recursion
match *self {
Query::def_span(..) => return span,
_ => ()
}
match *self {
$(Query::$name(key) => key.default_span(tcx),)*
}
}
}
impl<'a, $tcx> HashStable<StableHashingContext<'a>> for Query<$tcx> {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
$(Query::$name(key) => key.hash_stable(hcx, hasher),)*
}
}
}
pub mod queries {
use std::marker::PhantomData;
$(#[allow(bad_style)]
pub struct $name<$tcx> {
data: PhantomData<&$tcx ()>
})*
}
// This module and the functions in it exist only to provide a
// predictable symbol name prefix for query providers. This is helpful
// for analyzing queries in profilers.
pub(super) mod __query_compute {
$(#[inline(never)]
pub fn $name<F: FnOnce() -> R, R>(f: F) -> R {
f()
})*
}
$(impl<$tcx> QueryConfig<$tcx> for queries::$name<$tcx> {
type Key = $K;
type Value = $V;
const NAME: &'static str = stringify!($name);
}
impl<$tcx> QueryAccessors<$tcx> for queries::$name<$tcx> {
fn query(key: Self::Key) -> Query<'tcx> {
Query::$name(key)
}
fn query_cache<'a>(tcx: TyCtxt<'a, $tcx, '_>) -> &'a Lock<QueryCache<$tcx, Self>> {
&tcx.queries.$name
}
#[allow(unused)]
fn to_dep_node(tcx: TyCtxt<'_, $tcx, '_>, key: &Self::Key) -> DepNode {
use dep_graph::DepConstructor::*;
DepNode::new(tcx, $node(*key))
}
#[inline]
fn compute(tcx: TyCtxt<'_, 'tcx, '_>, key: Self::Key) -> Self::Value {
__query_compute::$name(move || {
let provider = tcx.queries.providers[key.query_crate()].$name;
provider(tcx.global_tcx(), key)
})
}
fn handle_cycle_error(tcx: TyCtxt<'_, 'tcx, '_>) -> Self::Value {
handle_cycle_error!([$($modifiers)*][tcx])
}
}
impl<'a, $tcx, 'lcx> queries::$name<$tcx> {
/// Ensure that either this query has all green inputs or been executed.
/// Executing query::ensure(D) is considered a read of the dep-node D.
///
/// This function is particularly useful when executing passes for their
/// side-effects -- e.g., in order to report errors for erroneous programs.
///
/// Note: The optimization is only available during incr. comp.
pub fn ensure(tcx: TyCtxt<'a, $tcx, 'lcx>, key: $K) -> () {
tcx.ensure_query::<queries::$name>(key);
}
})*
#[derive(Copy, Clone)]
pub struct TyCtxtAt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
pub span: Span,
}
impl<'a, 'gcx, 'tcx> Deref for TyCtxtAt<'a, 'gcx, 'tcx> {
type Target = TyCtxt<'a, 'gcx, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.tcx
}
}
impl<'a, $tcx, 'lcx> TyCtxt<'a, $tcx, 'lcx> {
/// Return a transparent wrapper for `TyCtxt` which uses
/// `span` as the location of queries performed through it.
pub fn at(self, span: Span) -> TyCtxtAt<'a, $tcx, 'lcx> {
TyCtxtAt {
tcx: self,
span
}
}
$($(#[$attr])*
pub fn $name(self, key: $K) -> $V {
self.at(DUMMY_SP).$name(key)
})*
}
impl<'a, $tcx, 'lcx> TyCtxtAt<'a, $tcx, 'lcx> {
$($(#[$attr])*
pub fn $name(self, key: $K) -> $V {
self.tcx.get_query::<queries::$name>(self.span, key)
})*
}
define_provider_struct! {
tcx: $tcx,
input: ($(([$($modifiers)*] [$name] [$K] [$V]))*)
}
impl<$tcx> Copy for Providers<$tcx> {}
impl<$tcx> Clone for Providers<$tcx> {
fn clone(&self) -> Self { *self }
}
}
}
macro_rules! define_queries_struct {
(tcx: $tcx:tt,
input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
pub(crate) struct Queries<$tcx> {
/// This provides access to the incr. comp. on-disk cache for query results.
/// Do not access this directly. It is only meant to be used by
/// `DepGraph::try_mark_green()` and the query infrastructure.
pub(crate) on_disk_cache: OnDiskCache<'tcx>,
providers: IndexVec<CrateNum, Providers<$tcx>>,
$($(#[$attr])* $name: Lock<QueryCache<$tcx, queries::$name<$tcx>>>,)*
}
};
}
macro_rules! define_provider_struct {
(tcx: $tcx:tt,
input: ($(([$($modifiers:tt)*] [$name:ident] [$K:ty] [$R:ty]))*)) => {
pub struct Providers<$tcx> {
$(pub $name: for<'a> fn(TyCtxt<'a, $tcx, $tcx>, $K) -> $R,)*
}
impl<$tcx> Default for Providers<$tcx> {
fn default() -> Self {
$(fn $name<'a, $tcx>(_: TyCtxt<'a, $tcx, $tcx>, key: $K) -> $R {
bug!("tcx.{}({:?}) unsupported by its crate",
stringify!($name), key);
})*
Providers { $($name),* }
}
}
};
}
/// The red/green evaluation system will try to mark a specific DepNode in the
/// dependency graph as green by recursively trying to mark the dependencies of
/// that DepNode as green. While doing so, it will sometimes encounter a DepNode
/// where we don't know if it is red or green and we therefore actually have
/// to recompute its value in order to find out. Since the only piece of
/// information that we have at that point is the DepNode we are trying to
/// re-evaluate, we need some way to re-run a query from just that. This is what
/// `force_from_dep_node()` implements.
///
/// In the general case, a DepNode consists of a DepKind and an opaque
/// GUID/fingerprint that will uniquely identify the node. This GUID/fingerprint
/// is usually constructed by computing a stable hash of the query-key that the
/// DepNode corresponds to. Consequently, it is not in general possible to go
/// back from hash to query-key (since hash functions are not reversible). For
/// this reason `force_from_dep_node()` is expected to fail from time to time
/// because we just cannot find out, from the DepNode alone, what the
/// corresponding query-key is and therefore cannot re-run the query.
///
/// The system deals with this case letting `try_mark_green` fail which forces
/// the root query to be re-evaluated.
///
/// Now, if force_from_dep_node() would always fail, it would be pretty useless.
/// Fortunately, we can use some contextual information that will allow us to
/// reconstruct query-keys for certain kinds of DepNodes. In particular, we
/// enforce by construction that the GUID/fingerprint of certain DepNodes is a
/// valid DefPathHash. Since we also always build a huge table that maps every
/// DefPathHash in the current codebase to the corresponding DefId, we have
/// everything we need to re-run the query.
///
/// Take the `mir_validated` query as an example. Like many other queries, it
/// just has a single parameter: the DefId of the item it will compute the
/// validated MIR for. Now, when we call `force_from_dep_node()` on a dep-node
/// with kind `MirValidated`, we know that the GUID/fingerprint of the dep-node
/// is actually a DefPathHash, and can therefore just look up the corresponding
/// DefId in `tcx.def_path_hash_to_def_id`.
///
/// When you implement a new query, it will likely have a corresponding new
/// DepKind, and you'll have to support it here in `force_from_dep_node()`. As
/// a rule of thumb, if your query takes a DefId or DefIndex as sole parameter,
/// then `force_from_dep_node()` should not fail for it. Otherwise, you can just
/// add it to the "We don't have enough information to reconstruct..." group in
/// the match below.
pub fn force_from_dep_node<'a, 'gcx, 'lcx>(tcx: TyCtxt<'a, 'gcx, 'lcx>,
dep_node: &DepNode)
-> bool {
use hir::def_id::LOCAL_CRATE;
// We must avoid ever having to call force_from_dep_node() for a
// DepNode::CodegenUnit:
// Since we cannot reconstruct the query key of a DepNode::CodegenUnit, we
// would always end up having to evaluate the first caller of the
// `codegen_unit` query that *is* reconstructible. This might very well be
// the `compile_codegen_unit` query, thus re-codegenning the whole CGU just
// to re-trigger calling the `codegen_unit` query with the right key. At
// that point we would already have re-done all the work we are trying to
// avoid doing in the first place.
// The solution is simple: Just explicitly call the `codegen_unit` query for
// each CGU, right after partitioning. This way `try_mark_green` will always
// hit the cache instead of having to go through `force_from_dep_node`.
// This assertion makes sure, we actually keep applying the solution above.
debug_assert!(dep_node.kind != DepKind::CodegenUnit,
"calling force_from_dep_node() on DepKind::CodegenUnit");
if !dep_node.kind.can_reconstruct_query_key() {
return false
}
macro_rules! def_id {
() => {
if let Some(def_id) = dep_node.extract_def_id(tcx) {
def_id
} else {
// return from the whole function
return false
}
}
};
macro_rules! krate {
() => { (def_id!()).krate }
};
macro_rules! force {
($query:ident, $key:expr) => {
{
use $crate::util::common::{ProfileQueriesMsg, profq_msg};
profq_msg!(tcx,
ProfileQueriesMsg::QueryBegin(
DUMMY_SP.data(),
profq_query_msg!(::ty::query::queries::$query::NAME, tcx, $key),
)
);
match tcx.force_query::<::ty::query::queries::$query>($key, DUMMY_SP, *dep_node) {
Ok(_) => {},
Err(e) => {
tcx.report_cycle(e).emit();
}
}
}
}
};
// FIXME(#45015): We should try move this boilerplate code into a macro
// somehow.
match dep_node.kind {
// These are inputs that are expected to be pre-allocated and that
// should therefore always be red or green already
DepKind::AllLocalTraitImpls |
DepKind::Krate |
DepKind::CrateMetadata |