]> git.lizzy.rs Git - rust.git/blob - src/librustc_middle/ty/query/profiling_support.rs
pin docs: add some forward references
[rust.git] / src / librustc_middle / ty / query / profiling_support.rs
1 use crate::ty::context::TyCtxt;
2 use measureme::{StringComponent, StringId};
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_data_structures::profiling::SelfProfiler;
5 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
6 use rustc_hir::definitions::DefPathData;
7 use rustc_query_system::query::QueryCache;
8 use rustc_query_system::query::QueryState;
9 use std::fmt::Debug;
10 use std::io::Write;
11
12 pub struct QueryKeyStringCache {
13     def_id_cache: FxHashMap<DefId, StringId>,
14 }
15
16 impl QueryKeyStringCache {
17     pub fn new() -> QueryKeyStringCache {
18         QueryKeyStringCache { def_id_cache: Default::default() }
19     }
20 }
21
22 pub struct QueryKeyStringBuilder<'p, 'c, 'tcx> {
23     profiler: &'p SelfProfiler,
24     tcx: TyCtxt<'tcx>,
25     string_cache: &'c mut QueryKeyStringCache,
26 }
27
28 impl<'p, 'c, 'tcx> QueryKeyStringBuilder<'p, 'c, 'tcx> {
29     pub fn new(
30         profiler: &'p SelfProfiler,
31         tcx: TyCtxt<'tcx>,
32         string_cache: &'c mut QueryKeyStringCache,
33     ) -> QueryKeyStringBuilder<'p, 'c, 'tcx> {
34         QueryKeyStringBuilder { profiler, tcx, string_cache }
35     }
36
37     // The current implementation is rather crude. In the future it might be a
38     // good idea to base this on `ty::print` in order to get nicer and more
39     // efficient query keys.
40     fn def_id_to_string_id(&mut self, def_id: DefId) -> StringId {
41         if let Some(&string_id) = self.string_cache.def_id_cache.get(&def_id) {
42             return string_id;
43         }
44
45         let def_key = self.tcx.def_key(def_id);
46
47         let (parent_string_id, start_index) = match def_key.parent {
48             Some(parent_index) => {
49                 let parent_def_id = DefId { index: parent_index, krate: def_id.krate };
50
51                 (self.def_id_to_string_id(parent_def_id), 0)
52             }
53             None => (StringId::INVALID, 2),
54         };
55
56         let dis_buffer = &mut [0u8; 16];
57         let name;
58         let dis;
59         let end_index;
60
61         match def_key.disambiguated_data.data {
62             DefPathData::CrateRoot => {
63                 name = self.tcx.original_crate_name(def_id.krate);
64                 dis = "";
65                 end_index = 3;
66             }
67             other => {
68                 name = other.as_symbol();
69                 if def_key.disambiguated_data.disambiguator == 0 {
70                     dis = "";
71                     end_index = 3;
72                 } else {
73                     write!(&mut dis_buffer[..], "[{}]", def_key.disambiguated_data.disambiguator)
74                         .unwrap();
75                     let end_of_dis = dis_buffer.iter().position(|&c| c == b']').unwrap();
76                     dis = std::str::from_utf8(&dis_buffer[..end_of_dis + 1]).unwrap();
77                     end_index = 4;
78                 }
79             }
80         }
81
82         let name = &*name.as_str();
83         let components = [
84             StringComponent::Ref(parent_string_id),
85             StringComponent::Value("::"),
86             StringComponent::Value(name),
87             StringComponent::Value(dis),
88         ];
89
90         let string_id = self.profiler.alloc_string(&components[start_index..end_index]);
91
92         self.string_cache.def_id_cache.insert(def_id, string_id);
93
94         string_id
95     }
96 }
97
98 pub trait IntoSelfProfilingString {
99     fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId;
100 }
101
102 // The default implementation of `IntoSelfProfilingString` just uses `Debug`
103 // which is slow and causes lots of duplication of string data.
104 // The specialized impls below take care of making the `DefId` case more
105 // efficient.
106 impl<T: Debug> IntoSelfProfilingString for T {
107     default fn to_self_profile_string(
108         &self,
109         builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
110     ) -> StringId {
111         let s = format!("{:?}", self);
112         builder.profiler.alloc_string(&s[..])
113     }
114 }
115
116 impl<T: SpecIntoSelfProfilingString> IntoSelfProfilingString for T {
117     fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId {
118         self.spec_to_self_profile_string(builder)
119     }
120 }
121
122 #[rustc_specialization_trait]
123 pub trait SpecIntoSelfProfilingString: Debug {
124     fn spec_to_self_profile_string(
125         &self,
126         builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
127     ) -> StringId;
128 }
129
130 impl SpecIntoSelfProfilingString for DefId {
131     fn spec_to_self_profile_string(
132         &self,
133         builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
134     ) -> StringId {
135         builder.def_id_to_string_id(*self)
136     }
137 }
138
139 impl SpecIntoSelfProfilingString for CrateNum {
140     fn spec_to_self_profile_string(
141         &self,
142         builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
143     ) -> StringId {
144         builder.def_id_to_string_id(DefId { krate: *self, index: CRATE_DEF_INDEX })
145     }
146 }
147
148 impl SpecIntoSelfProfilingString for DefIndex {
149     fn spec_to_self_profile_string(
150         &self,
151         builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
152     ) -> StringId {
153         builder.def_id_to_string_id(DefId { krate: LOCAL_CRATE, index: *self })
154     }
155 }
156
157 impl<T0, T1> SpecIntoSelfProfilingString for (T0, T1)
158 where
159     T0: SpecIntoSelfProfilingString,
160     T1: SpecIntoSelfProfilingString,
161 {
162     fn spec_to_self_profile_string(
163         &self,
164         builder: &mut QueryKeyStringBuilder<'_, '_, '_>,
165     ) -> StringId {
166         let val0 = self.0.to_self_profile_string(builder);
167         let val1 = self.1.to_self_profile_string(builder);
168
169         let components = &[
170             StringComponent::Value("("),
171             StringComponent::Ref(val0),
172             StringComponent::Value(","),
173             StringComponent::Ref(val1),
174             StringComponent::Value(")"),
175         ];
176
177         builder.profiler.alloc_string(components)
178     }
179 }
180
181 /// Allocate the self-profiling query strings for a single query cache. This
182 /// method is called from `alloc_self_profile_query_strings` which knows all
183 /// the queries via macro magic.
184 pub(super) fn alloc_self_profile_query_strings_for_query_cache<'tcx, C>(
185     tcx: TyCtxt<'tcx>,
186     query_name: &'static str,
187     query_state: &QueryState<TyCtxt<'tcx>, C>,
188     string_cache: &mut QueryKeyStringCache,
189 ) where
190     C: QueryCache,
191     C::Key: Debug + Clone,
192 {
193     tcx.prof.with_profiler(|profiler| {
194         let event_id_builder = profiler.event_id_builder();
195
196         // Walk the entire query cache and allocate the appropriate
197         // string representations. Each cache entry is uniquely
198         // identified by its dep_node_index.
199         if profiler.query_key_recording_enabled() {
200             let mut query_string_builder = QueryKeyStringBuilder::new(profiler, tcx, string_cache);
201
202             let query_name = profiler.get_or_alloc_cached_string(query_name);
203
204             // Since building the string representation of query keys might
205             // need to invoke queries itself, we cannot keep the query caches
206             // locked while doing so. Instead we copy out the
207             // `(query_key, dep_node_index)` pairs and release the lock again.
208             let query_keys_and_indices: Vec<_> = query_state
209                 .iter_results(|results| results.map(|(k, _, i)| (k.clone(), i)).collect());
210
211             // Now actually allocate the strings. If allocating the strings
212             // generates new entries in the query cache, we'll miss them but
213             // we don't actually care.
214             for (query_key, dep_node_index) in query_keys_and_indices {
215                 // Translate the DepNodeIndex into a QueryInvocationId
216                 let query_invocation_id = dep_node_index.into();
217
218                 // Create the string version of the query-key
219                 let query_key = query_key.to_self_profile_string(&mut query_string_builder);
220                 let event_id = event_id_builder.from_label_and_arg(query_name, query_key);
221
222                 // Doing this in bulk might be a good idea:
223                 profiler.map_query_invocation_id_to_string(
224                     query_invocation_id,
225                     event_id.to_string_id(),
226                 );
227             }
228         } else {
229             // In this branch we don't allocate query keys
230             let query_name = profiler.get_or_alloc_cached_string(query_name);
231             let event_id = event_id_builder.from_label(query_name).to_string_id();
232
233             query_state.iter_results(|results| {
234                 let query_invocation_ids: Vec<_> = results.map(|v| v.2.into()).collect();
235
236                 profiler.bulk_map_query_invocation_id_to_single_string(
237                     query_invocation_ids.into_iter(),
238                     event_id,
239                 );
240             });
241         }
242     });
243 }