]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/profiling.rs
Rollup merge of #105369 - chenyukang:yukang/fix-105226, r=TaKO8Ki
[rust.git] / compiler / rustc_data_structures / src / profiling.rs
1 //! # Rust Compiler Self-Profiling
2 //!
3 //! This module implements the basic framework for the compiler's self-
4 //! profiling support. It provides the `SelfProfiler` type which enables
5 //! recording "events". An event is something that starts and ends at a given
6 //! point in time and has an ID and a kind attached to it. This allows for
7 //! tracing the compiler's activity.
8 //!
9 //! Internally this module uses the custom tailored [measureme][mm] crate for
10 //! efficiently recording events to disk in a compact format that can be
11 //! post-processed and analyzed by the suite of tools in the `measureme`
12 //! project. The highest priority for the tracing framework is on incurring as
13 //! little overhead as possible.
14 //!
15 //!
16 //! ## Event Overview
17 //!
18 //! Events have a few properties:
19 //!
20 //! - The `event_kind` designates the broad category of an event (e.g. does it
21 //!   correspond to the execution of a query provider or to loading something
22 //!   from the incr. comp. on-disk cache, etc).
23 //! - The `event_id` designates the query invocation or function call it
24 //!   corresponds to, possibly including the query key or function arguments.
25 //! - Each event stores the ID of the thread it was recorded on.
26 //! - The timestamp stores beginning and end of the event, or the single point
27 //!   in time it occurred at for "instant" events.
28 //!
29 //!
30 //! ## Event Filtering
31 //!
32 //! Event generation can be filtered by event kind. Recording all possible
33 //! events generates a lot of data, much of which is not needed for most kinds
34 //! of analysis. So, in order to keep overhead as low as possible for a given
35 //! use case, the `SelfProfiler` will only record the kinds of events that
36 //! pass the filter specified as a command line argument to the compiler.
37 //!
38 //!
39 //! ## `event_id` Assignment
40 //!
41 //! As far as `measureme` is concerned, `event_id`s are just strings. However,
42 //! it would incur too much overhead to generate and persist each `event_id`
43 //! string at the point where the event is recorded. In order to make this more
44 //! efficient `measureme` has two features:
45 //!
46 //! - Strings can share their content, so that re-occurring parts don't have to
47 //!   be copied over and over again. One allocates a string in `measureme` and
48 //!   gets back a `StringId`. This `StringId` is then used to refer to that
49 //!   string. `measureme` strings are actually DAGs of string components so that
50 //!   arbitrary sharing of substrings can be done efficiently. This is useful
51 //!   because `event_id`s contain lots of redundant text like query names or
52 //!   def-path components.
53 //!
54 //! - `StringId`s can be "virtual" which means that the client picks a numeric
55 //!   ID according to some application-specific scheme and can later make that
56 //!   ID be mapped to an actual string. This is used to cheaply generate
57 //!   `event_id`s while the events actually occur, causing little timing
58 //!   distortion, and then later map those `StringId`s, in bulk, to actual
59 //!   `event_id` strings. This way the largest part of the tracing overhead is
60 //!   localized to one contiguous chunk of time.
61 //!
62 //! How are these `event_id`s generated in the compiler? For things that occur
63 //! infrequently (e.g. "generic activities"), we just allocate the string the
64 //! first time it is used and then keep the `StringId` in a hash table. This
65 //! is implemented in `SelfProfiler::get_or_alloc_cached_string()`.
66 //!
67 //! For queries it gets more interesting: First we need a unique numeric ID for
68 //! each query invocation (the `QueryInvocationId`). This ID is used as the
69 //! virtual `StringId` we use as `event_id` for a given event. This ID has to
70 //! be available both when the query is executed and later, together with the
71 //! query key, when we allocate the actual `event_id` strings in bulk.
72 //!
73 //! We could make the compiler generate and keep track of such an ID for each
74 //! query invocation but luckily we already have something that fits all the
75 //! the requirements: the query's `DepNodeIndex`. So we use the numeric value
76 //! of the `DepNodeIndex` as `event_id` when recording the event and then,
77 //! just before the query context is dropped, we walk the entire query cache
78 //! (which stores the `DepNodeIndex` along with the query key for each
79 //! invocation) and allocate the corresponding strings together with a mapping
80 //! for `DepNodeIndex as StringId`.
81 //!
82 //! [mm]: https://github.com/rust-lang/measureme/
83
84 use crate::cold_path;
85 use crate::fx::FxHashMap;
86
87 use std::borrow::Borrow;
88 use std::collections::hash_map::Entry;
89 use std::error::Error;
90 use std::fs;
91 use std::path::Path;
92 use std::process;
93 use std::sync::Arc;
94 use std::time::{Duration, Instant};
95
96 pub use measureme::EventId;
97 use measureme::{EventIdBuilder, Profiler, SerializableString, StringId};
98 use parking_lot::RwLock;
99 use smallvec::SmallVec;
100
101 bitflags::bitflags! {
102     struct EventFilter: u32 {
103         const GENERIC_ACTIVITIES  = 1 << 0;
104         const QUERY_PROVIDERS     = 1 << 1;
105         const QUERY_CACHE_HITS    = 1 << 2;
106         const QUERY_BLOCKED       = 1 << 3;
107         const INCR_CACHE_LOADS    = 1 << 4;
108
109         const QUERY_KEYS          = 1 << 5;
110         const FUNCTION_ARGS       = 1 << 6;
111         const LLVM                = 1 << 7;
112         const INCR_RESULT_HASHING = 1 << 8;
113         const ARTIFACT_SIZES = 1 << 9;
114
115         const DEFAULT = Self::GENERIC_ACTIVITIES.bits |
116                         Self::QUERY_PROVIDERS.bits |
117                         Self::QUERY_BLOCKED.bits |
118                         Self::INCR_CACHE_LOADS.bits |
119                         Self::INCR_RESULT_HASHING.bits |
120                         Self::ARTIFACT_SIZES.bits;
121
122         const ARGS = Self::QUERY_KEYS.bits | Self::FUNCTION_ARGS.bits;
123     }
124 }
125
126 // keep this in sync with the `-Z self-profile-events` help message in rustc_session/options.rs
127 const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
128     ("none", EventFilter::empty()),
129     ("all", EventFilter::all()),
130     ("default", EventFilter::DEFAULT),
131     ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
132     ("query-provider", EventFilter::QUERY_PROVIDERS),
133     ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
134     ("query-blocked", EventFilter::QUERY_BLOCKED),
135     ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
136     ("query-keys", EventFilter::QUERY_KEYS),
137     ("function-args", EventFilter::FUNCTION_ARGS),
138     ("args", EventFilter::ARGS),
139     ("llvm", EventFilter::LLVM),
140     ("incr-result-hashing", EventFilter::INCR_RESULT_HASHING),
141     ("artifact-sizes", EventFilter::ARTIFACT_SIZES),
142 ];
143
144 /// Something that uniquely identifies a query invocation.
145 pub struct QueryInvocationId(pub u32);
146
147 /// A reference to the SelfProfiler. It can be cloned and sent across thread
148 /// boundaries at will.
149 #[derive(Clone)]
150 pub struct SelfProfilerRef {
151     // This field is `None` if self-profiling is disabled for the current
152     // compilation session.
153     profiler: Option<Arc<SelfProfiler>>,
154
155     // We store the filter mask directly in the reference because that doesn't
156     // cost anything and allows for filtering with checking if the profiler is
157     // actually enabled.
158     event_filter_mask: EventFilter,
159
160     // Print verbose generic activities to stderr?
161     print_verbose_generic_activities: bool,
162 }
163
164 impl SelfProfilerRef {
165     pub fn new(
166         profiler: Option<Arc<SelfProfiler>>,
167         print_verbose_generic_activities: bool,
168     ) -> SelfProfilerRef {
169         // If there is no SelfProfiler then the filter mask is set to NONE,
170         // ensuring that nothing ever tries to actually access it.
171         let event_filter_mask =
172             profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask);
173
174         SelfProfilerRef { profiler, event_filter_mask, print_verbose_generic_activities }
175     }
176
177     /// This shim makes sure that calls only get executed if the filter mask
178     /// lets them pass. It also contains some trickery to make sure that
179     /// code is optimized for non-profiling compilation sessions, i.e. anything
180     /// past the filter check is never inlined so it doesn't clutter the fast
181     /// path.
182     #[inline(always)]
183     fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
184     where
185         F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
186     {
187         #[inline(never)]
188         #[cold]
189         fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
190         where
191             F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
192         {
193             let profiler = profiler_ref.profiler.as_ref().unwrap();
194             f(profiler)
195         }
196
197         if self.event_filter_mask.contains(event_filter) {
198             cold_call(self, f)
199         } else {
200             TimingGuard::none()
201         }
202     }
203
204     /// Start profiling a verbose generic activity. Profiling continues until the
205     /// VerboseTimingGuard returned from this call is dropped. In addition to recording
206     /// a measureme event, "verbose" generic activities also print a timing entry to
207     /// stderr if the compiler is invoked with -Ztime-passes.
208     pub fn verbose_generic_activity<'a>(
209         &'a self,
210         event_label: &'static str,
211     ) -> VerboseTimingGuard<'a> {
212         let message =
213             if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None };
214
215         VerboseTimingGuard::start(message, self.generic_activity(event_label))
216     }
217
218     /// Like `verbose_generic_activity`, but with an extra arg.
219     pub fn verbose_generic_activity_with_arg<'a, A>(
220         &'a self,
221         event_label: &'static str,
222         event_arg: A,
223     ) -> VerboseTimingGuard<'a>
224     where
225         A: Borrow<str> + Into<String>,
226     {
227         let message = if self.print_verbose_generic_activities {
228             Some(format!("{}({})", event_label, event_arg.borrow()))
229         } else {
230             None
231         };
232
233         VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg))
234     }
235
236     /// Start profiling a generic activity. Profiling continues until the
237     /// TimingGuard returned from this call is dropped.
238     #[inline(always)]
239     pub fn generic_activity(&self, event_label: &'static str) -> TimingGuard<'_> {
240         self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
241             let event_label = profiler.get_or_alloc_cached_string(event_label);
242             let event_id = EventId::from_label(event_label);
243             TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
244         })
245     }
246
247     /// Start profiling with some event filter for a given event. Profiling continues until the
248     /// TimingGuard returned from this call is dropped.
249     #[inline(always)]
250     pub fn generic_activity_with_event_id(&self, event_id: EventId) -> TimingGuard<'_> {
251         self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
252             TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
253         })
254     }
255
256     /// Start profiling a generic activity. Profiling continues until the
257     /// TimingGuard returned from this call is dropped.
258     #[inline(always)]
259     pub fn generic_activity_with_arg<A>(
260         &self,
261         event_label: &'static str,
262         event_arg: A,
263     ) -> TimingGuard<'_>
264     where
265         A: Borrow<str> + Into<String>,
266     {
267         self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
268             let builder = EventIdBuilder::new(&profiler.profiler);
269             let event_label = profiler.get_or_alloc_cached_string(event_label);
270             let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
271                 let event_arg = profiler.get_or_alloc_cached_string(event_arg);
272                 builder.from_label_and_arg(event_label, event_arg)
273             } else {
274                 builder.from_label(event_label)
275             };
276             TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
277         })
278     }
279
280     /// Start profiling a generic activity, allowing costly arguments to be recorded. Profiling
281     /// continues until the `TimingGuard` returned from this call is dropped.
282     ///
283     /// If the arguments to a generic activity are cheap to create, use `generic_activity_with_arg`
284     /// or `generic_activity_with_args` for their simpler API. However, if they are costly or
285     /// require allocation in sufficiently hot contexts, then this allows for a closure to be called
286     /// only when arguments were asked to be recorded via `-Z self-profile-events=args`.
287     ///
288     /// In this case, the closure will be passed a `&mut EventArgRecorder`, to help with recording
289     /// one or many arguments within the generic activity being profiled, by calling its
290     /// `record_arg` method for example.
291     ///
292     /// This `EventArgRecorder` may implement more specific traits from other rustc crates, e.g. for
293     /// richer handling of rustc-specific argument types, while keeping this single entry-point API
294     /// for recording arguments.
295     ///
296     /// Note: recording at least one argument is *required* for the self-profiler to create the
297     /// `TimingGuard`. A panic will be triggered if that doesn't happen. This function exists
298     /// explicitly to record arguments, so it fails loudly when there are none to record.
299     ///
300     #[inline(always)]
301     pub fn generic_activity_with_arg_recorder<F>(
302         &self,
303         event_label: &'static str,
304         mut f: F,
305     ) -> TimingGuard<'_>
306     where
307         F: FnMut(&mut EventArgRecorder<'_>),
308     {
309         // Ensure this event will only be recorded when self-profiling is turned on.
310         self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
311             let builder = EventIdBuilder::new(&profiler.profiler);
312             let event_label = profiler.get_or_alloc_cached_string(event_label);
313
314             // Ensure the closure to create event arguments will only be called when argument
315             // recording is turned on.
316             let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
317                 // Set up the builder and call the user-provided closure to record potentially
318                 // costly event arguments.
319                 let mut recorder = EventArgRecorder { profiler, args: SmallVec::new() };
320                 f(&mut recorder);
321
322                 // It is expected that the closure will record at least one argument. If that
323                 // doesn't happen, it's a bug: we've been explicitly called in order to record
324                 // arguments, so we fail loudly when there are none to record.
325                 if recorder.args.is_empty() {
326                     panic!(
327                         "The closure passed to `generic_activity_with_arg_recorder` needs to \
328                          record at least one argument"
329                     );
330                 }
331
332                 builder.from_label_and_args(event_label, &recorder.args)
333             } else {
334                 builder.from_label(event_label)
335             };
336             TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
337         })
338     }
339
340     /// Record the size of an artifact that the compiler produces
341     ///
342     /// `artifact_kind` is the class of artifact (e.g., query_cache, object_file, etc.)
343     /// `artifact_name` is an identifier to the specific artifact being stored (usually a filename)
344     #[inline(always)]
345     pub fn artifact_size<A>(&self, artifact_kind: &str, artifact_name: A, size: u64)
346     where
347         A: Borrow<str> + Into<String>,
348     {
349         drop(self.exec(EventFilter::ARTIFACT_SIZES, |profiler| {
350             let builder = EventIdBuilder::new(&profiler.profiler);
351             let event_label = profiler.get_or_alloc_cached_string(artifact_kind);
352             let event_arg = profiler.get_or_alloc_cached_string(artifact_name);
353             let event_id = builder.from_label_and_arg(event_label, event_arg);
354             let thread_id = get_thread_id();
355
356             profiler.profiler.record_integer_event(
357                 profiler.artifact_size_event_kind,
358                 event_id,
359                 thread_id,
360                 size,
361             );
362
363             TimingGuard::none()
364         }))
365     }
366
367     #[inline(always)]
368     pub fn generic_activity_with_args(
369         &self,
370         event_label: &'static str,
371         event_args: &[String],
372     ) -> TimingGuard<'_> {
373         self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
374             let builder = EventIdBuilder::new(&profiler.profiler);
375             let event_label = profiler.get_or_alloc_cached_string(event_label);
376             let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
377                 let event_args: Vec<_> = event_args
378                     .iter()
379                     .map(|s| profiler.get_or_alloc_cached_string(&s[..]))
380                     .collect();
381                 builder.from_label_and_args(event_label, &event_args)
382             } else {
383                 builder.from_label(event_label)
384             };
385             TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
386         })
387     }
388
389     /// Start profiling a query provider. Profiling continues until the
390     /// TimingGuard returned from this call is dropped.
391     #[inline(always)]
392     pub fn query_provider(&self) -> TimingGuard<'_> {
393         self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
394             TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
395         })
396     }
397
398     /// Record a query in-memory cache hit.
399     #[inline(always)]
400     pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
401         self.instant_query_event(
402             |profiler| profiler.query_cache_hit_event_kind,
403             query_invocation_id,
404             EventFilter::QUERY_CACHE_HITS,
405         );
406     }
407
408     /// Start profiling a query being blocked on a concurrent execution.
409     /// Profiling continues until the TimingGuard returned from this call is
410     /// dropped.
411     #[inline(always)]
412     pub fn query_blocked(&self) -> TimingGuard<'_> {
413         self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
414             TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
415         })
416     }
417
418     /// Start profiling how long it takes to load a query result from the
419     /// incremental compilation on-disk cache. Profiling continues until the
420     /// TimingGuard returned from this call is dropped.
421     #[inline(always)]
422     pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
423         self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
424             TimingGuard::start(
425                 profiler,
426                 profiler.incremental_load_result_event_kind,
427                 EventId::INVALID,
428             )
429         })
430     }
431
432     /// Start profiling how long it takes to hash query results for incremental compilation.
433     /// Profiling continues until the TimingGuard returned from this call is dropped.
434     #[inline(always)]
435     pub fn incr_result_hashing(&self) -> TimingGuard<'_> {
436         self.exec(EventFilter::INCR_RESULT_HASHING, |profiler| {
437             TimingGuard::start(
438                 profiler,
439                 profiler.incremental_result_hashing_event_kind,
440                 EventId::INVALID,
441             )
442         })
443     }
444
445     #[inline(always)]
446     fn instant_query_event(
447         &self,
448         event_kind: fn(&SelfProfiler) -> StringId,
449         query_invocation_id: QueryInvocationId,
450         event_filter: EventFilter,
451     ) {
452         drop(self.exec(event_filter, |profiler| {
453             let event_id = StringId::new_virtual(query_invocation_id.0);
454             let thread_id = get_thread_id();
455
456             profiler.profiler.record_instant_event(
457                 event_kind(profiler),
458                 EventId::from_virtual(event_id),
459                 thread_id,
460             );
461
462             TimingGuard::none()
463         }));
464     }
465
466     pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
467         if let Some(profiler) = &self.profiler {
468             f(profiler)
469         }
470     }
471
472     /// Gets a `StringId` for the given string. This method makes sure that
473     /// any strings going through it will only be allocated once in the
474     /// profiling data.
475     /// Returns `None` if the self-profiling is not enabled.
476     pub fn get_or_alloc_cached_string(&self, s: &str) -> Option<StringId> {
477         self.profiler.as_ref().map(|p| p.get_or_alloc_cached_string(s))
478     }
479
480     #[inline]
481     pub fn enabled(&self) -> bool {
482         self.profiler.is_some()
483     }
484
485     #[inline]
486     pub fn llvm_recording_enabled(&self) -> bool {
487         self.event_filter_mask.contains(EventFilter::LLVM)
488     }
489     #[inline]
490     pub fn get_self_profiler(&self) -> Option<Arc<SelfProfiler>> {
491         self.profiler.clone()
492     }
493 }
494
495 /// A helper for recording costly arguments to self-profiling events. Used with
496 /// `SelfProfilerRef::generic_activity_with_arg_recorder`.
497 pub struct EventArgRecorder<'p> {
498     /// The `SelfProfiler` used to intern the event arguments that users will ask to record.
499     profiler: &'p SelfProfiler,
500
501     /// The interned event arguments to be recorded in the generic activity event.
502     ///
503     /// The most common case, when actually recording event arguments, is to have one argument. Then
504     /// followed by recording two, in a couple places.
505     args: SmallVec<[StringId; 2]>,
506 }
507
508 impl EventArgRecorder<'_> {
509     /// Records a single argument within the current generic activity being profiled.
510     ///
511     /// Note: when self-profiling with costly event arguments, at least one argument
512     /// needs to be recorded. A panic will be triggered if that doesn't happen.
513     pub fn record_arg<A>(&mut self, event_arg: A)
514     where
515         A: Borrow<str> + Into<String>,
516     {
517         let event_arg = self.profiler.get_or_alloc_cached_string(event_arg);
518         self.args.push(event_arg);
519     }
520 }
521
522 pub struct SelfProfiler {
523     profiler: Profiler,
524     event_filter_mask: EventFilter,
525
526     string_cache: RwLock<FxHashMap<String, StringId>>,
527
528     query_event_kind: StringId,
529     generic_activity_event_kind: StringId,
530     incremental_load_result_event_kind: StringId,
531     incremental_result_hashing_event_kind: StringId,
532     query_blocked_event_kind: StringId,
533     query_cache_hit_event_kind: StringId,
534     artifact_size_event_kind: StringId,
535 }
536
537 impl SelfProfiler {
538     pub fn new(
539         output_directory: &Path,
540         crate_name: Option<&str>,
541         event_filters: Option<&[String]>,
542         counter_name: &str,
543     ) -> Result<SelfProfiler, Box<dyn Error + Send + Sync>> {
544         fs::create_dir_all(output_directory)?;
545
546         let crate_name = crate_name.unwrap_or("unknown-crate");
547         // HACK(eddyb) we need to pad the PID, strange as it may seem, as its
548         // length can behave as a source of entropy for heap addresses, when
549         // ASLR is disabled and the heap is otherwise determinic.
550         let pid: u32 = process::id();
551         let filename = format!("{}-{:07}.rustc_profile", crate_name, pid);
552         let path = output_directory.join(&filename);
553         let profiler =
554             Profiler::with_counter(&path, measureme::counters::Counter::by_name(counter_name)?)?;
555
556         let query_event_kind = profiler.alloc_string("Query");
557         let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
558         let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
559         let incremental_result_hashing_event_kind =
560             profiler.alloc_string("IncrementalResultHashing");
561         let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
562         let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
563         let artifact_size_event_kind = profiler.alloc_string("ArtifactSize");
564
565         let mut event_filter_mask = EventFilter::empty();
566
567         if let Some(event_filters) = event_filters {
568             let mut unknown_events = vec![];
569             for item in event_filters {
570                 if let Some(&(_, mask)) =
571                     EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
572                 {
573                     event_filter_mask |= mask;
574                 } else {
575                     unknown_events.push(item.clone());
576                 }
577             }
578
579             // Warn about any unknown event names
580             if !unknown_events.is_empty() {
581                 unknown_events.sort();
582                 unknown_events.dedup();
583
584                 warn!(
585                     "Unknown self-profiler events specified: {}. Available options are: {}.",
586                     unknown_events.join(", "),
587                     EVENT_FILTERS_BY_NAME
588                         .iter()
589                         .map(|&(name, _)| name.to_string())
590                         .collect::<Vec<_>>()
591                         .join(", ")
592                 );
593             }
594         } else {
595             event_filter_mask = EventFilter::DEFAULT;
596         }
597
598         Ok(SelfProfiler {
599             profiler,
600             event_filter_mask,
601             string_cache: RwLock::new(FxHashMap::default()),
602             query_event_kind,
603             generic_activity_event_kind,
604             incremental_load_result_event_kind,
605             incremental_result_hashing_event_kind,
606             query_blocked_event_kind,
607             query_cache_hit_event_kind,
608             artifact_size_event_kind,
609         })
610     }
611
612     /// Allocates a new string in the profiling data. Does not do any caching
613     /// or deduplication.
614     pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
615         self.profiler.alloc_string(s)
616     }
617
618     /// Gets a `StringId` for the given string. This method makes sure that
619     /// any strings going through it will only be allocated once in the
620     /// profiling data.
621     pub fn get_or_alloc_cached_string<A>(&self, s: A) -> StringId
622     where
623         A: Borrow<str> + Into<String>,
624     {
625         // Only acquire a read-lock first since we assume that the string is
626         // already present in the common case.
627         {
628             let string_cache = self.string_cache.read();
629
630             if let Some(&id) = string_cache.get(s.borrow()) {
631                 return id;
632             }
633         }
634
635         let mut string_cache = self.string_cache.write();
636         // Check if the string has already been added in the small time window
637         // between dropping the read lock and acquiring the write lock.
638         match string_cache.entry(s.into()) {
639             Entry::Occupied(e) => *e.get(),
640             Entry::Vacant(e) => {
641                 let string_id = self.profiler.alloc_string(&e.key()[..]);
642                 *e.insert(string_id)
643             }
644         }
645     }
646
647     pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
648         let from = StringId::new_virtual(from.0);
649         self.profiler.map_virtual_to_concrete_string(from, to);
650     }
651
652     pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
653     where
654         I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
655     {
656         let from = from.map(|qid| StringId::new_virtual(qid.0));
657         self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
658     }
659
660     pub fn query_key_recording_enabled(&self) -> bool {
661         self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
662     }
663
664     pub fn event_id_builder(&self) -> EventIdBuilder<'_> {
665         EventIdBuilder::new(&self.profiler)
666     }
667 }
668
669 #[must_use]
670 pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a>>);
671
672 impl<'a> TimingGuard<'a> {
673     #[inline]
674     pub fn start(
675         profiler: &'a SelfProfiler,
676         event_kind: StringId,
677         event_id: EventId,
678     ) -> TimingGuard<'a> {
679         let thread_id = get_thread_id();
680         let raw_profiler = &profiler.profiler;
681         let timing_guard =
682             raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
683         TimingGuard(Some(timing_guard))
684     }
685
686     #[inline]
687     pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
688         if let Some(guard) = self.0 {
689             cold_path(|| {
690                 let event_id = StringId::new_virtual(query_invocation_id.0);
691                 let event_id = EventId::from_virtual(event_id);
692                 guard.finish_with_override_event_id(event_id);
693             });
694         }
695     }
696
697     #[inline]
698     pub fn none() -> TimingGuard<'a> {
699         TimingGuard(None)
700     }
701
702     #[inline(always)]
703     pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
704         let _timer = self;
705         f()
706     }
707 }
708
709 #[must_use]
710 pub struct VerboseTimingGuard<'a> {
711     start_and_message: Option<(Instant, Option<usize>, String)>,
712     _guard: TimingGuard<'a>,
713 }
714
715 impl<'a> VerboseTimingGuard<'a> {
716     pub fn start(message: Option<String>, _guard: TimingGuard<'a>) -> Self {
717         VerboseTimingGuard {
718             _guard,
719             start_and_message: message.map(|msg| (Instant::now(), get_resident_set_size(), msg)),
720         }
721     }
722
723     #[inline(always)]
724     pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
725         let _timer = self;
726         f()
727     }
728 }
729
730 impl Drop for VerboseTimingGuard<'_> {
731     fn drop(&mut self) {
732         if let Some((start_time, start_rss, ref message)) = self.start_and_message {
733             let end_rss = get_resident_set_size();
734             let dur = start_time.elapsed();
735             print_time_passes_entry(message, dur, start_rss, end_rss);
736         }
737     }
738 }
739
740 pub fn print_time_passes_entry(
741     what: &str,
742     dur: Duration,
743     start_rss: Option<usize>,
744     end_rss: Option<usize>,
745 ) {
746     // Print the pass if its duration is greater than 5 ms, or it changed the
747     // measured RSS.
748     let is_notable = || {
749         if dur.as_millis() > 5 {
750             return true;
751         }
752
753         if let (Some(start_rss), Some(end_rss)) = (start_rss, end_rss) {
754             let change_rss = end_rss.abs_diff(start_rss);
755             if change_rss > 0 {
756                 return true;
757             }
758         }
759
760         false
761     };
762     if !is_notable() {
763         return;
764     }
765
766     let rss_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as usize;
767     let rss_change_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as i128;
768
769     let mem_string = match (start_rss, end_rss) {
770         (Some(start_rss), Some(end_rss)) => {
771             let change_rss = end_rss as i128 - start_rss as i128;
772
773             format!(
774                 "; rss: {:>4}MB -> {:>4}MB ({:>+5}MB)",
775                 rss_to_mb(start_rss),
776                 rss_to_mb(end_rss),
777                 rss_change_to_mb(change_rss),
778             )
779         }
780         (Some(start_rss), None) => format!("; rss start: {:>4}MB", rss_to_mb(start_rss)),
781         (None, Some(end_rss)) => format!("; rss end: {:>4}MB", rss_to_mb(end_rss)),
782         (None, None) => String::new(),
783     };
784
785     eprintln!("time: {:>7}{}\t{}", duration_to_secs_str(dur), mem_string, what);
786 }
787
788 // Hack up our own formatting for the duration to make it easier for scripts
789 // to parse (always use the same number of decimal places and the same unit).
790 pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
791     format!("{:.3}", dur.as_secs_f64())
792 }
793
794 fn get_thread_id() -> u32 {
795     std::thread::current().id().as_u64().get() as u32
796 }
797
798 // Memory reporting
799 cfg_if! {
800     if #[cfg(windows)] {
801         pub fn get_resident_set_size() -> Option<usize> {
802             use std::mem::{self, MaybeUninit};
803             use winapi::shared::minwindef::DWORD;
804             use winapi::um::processthreadsapi::GetCurrentProcess;
805             use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
806
807             let mut pmc = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
808             match unsafe {
809                 GetProcessMemoryInfo(GetCurrentProcess(), pmc.as_mut_ptr(), mem::size_of_val(&pmc) as DWORD)
810             } {
811                 0 => None,
812                 _ => {
813                     let pmc = unsafe { pmc.assume_init() };
814                     Some(pmc.WorkingSetSize as usize)
815                 }
816             }
817         }
818     } else if #[cfg(target_os = "macos")] {
819         pub fn get_resident_set_size() -> Option<usize> {
820             use libc::{c_int, c_void, getpid, proc_pidinfo, proc_taskinfo, PROC_PIDTASKINFO};
821             use std::mem;
822             const PROC_TASKINFO_SIZE: c_int = mem::size_of::<proc_taskinfo>() as c_int;
823
824             unsafe {
825                 let mut info: proc_taskinfo = mem::zeroed();
826                 let info_ptr = &mut info as *mut proc_taskinfo as *mut c_void;
827                 let pid = getpid() as c_int;
828                 let ret = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, info_ptr, PROC_TASKINFO_SIZE);
829                 if ret == PROC_TASKINFO_SIZE {
830                     Some(info.pti_resident_size as usize)
831                 } else {
832                     None
833                 }
834             }
835         }
836     } else if #[cfg(unix)] {
837         pub fn get_resident_set_size() -> Option<usize> {
838             let field = 1;
839             let contents = fs::read("/proc/self/statm").ok()?;
840             let contents = String::from_utf8(contents).ok()?;
841             let s = contents.split_whitespace().nth(field)?;
842             let npages = s.parse::<usize>().ok()?;
843             Some(npages * 4096)
844         }
845     } else {
846         pub fn get_resident_set_size() -> Option<usize> {
847             None
848         }
849     }
850 }