]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/profiling.rs
[self-profiler] Clean up `EventFilter`
[rust.git] / src / librustc_data_structures / 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::fx::FxHashMap;
85
86 use std::error::Error;
87 use std::fs;
88 use std::path::Path;
89 use std::process;
90 use std::sync::Arc;
91 use std::time::{Duration, Instant};
92 use std::u32;
93
94 use measureme::{EventId, EventIdBuilder, SerializableString, StringId};
95 use parking_lot::RwLock;
96
97 /// MmapSerializatioSink is faster on macOS and Linux
98 /// but FileSerializationSink is faster on Windows
99 #[cfg(not(windows))]
100 type SerializationSink = measureme::MmapSerializationSink;
101 #[cfg(windows)]
102 type SerializationSink = measureme::FileSerializationSink;
103
104 type Profiler = measureme::Profiler<SerializationSink>;
105
106 #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
107 pub enum ProfileCategory {
108     Parsing,
109     Expansion,
110     TypeChecking,
111     BorrowChecking,
112     Codegen,
113     Linking,
114     Other,
115 }
116
117 bitflags::bitflags! {
118     struct EventFilter: u32 {
119         const GENERIC_ACTIVITIES = 1 << 0;
120         const QUERY_PROVIDERS    = 1 << 1;
121         const QUERY_CACHE_HITS   = 1 << 2;
122         const QUERY_BLOCKED      = 1 << 3;
123         const INCR_CACHE_LOADS   = 1 << 4;
124
125         const QUERY_KEYS         = 1 << 5;
126
127         const DEFAULT = Self::GENERIC_ACTIVITIES.bits |
128                         Self::QUERY_PROVIDERS.bits |
129                         Self::QUERY_BLOCKED.bits |
130                         Self::INCR_CACHE_LOADS.bits;
131     }
132 }
133
134 // keep this in sync with the `-Z self-profile-events` help message in librustc_session/options.rs
135 const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
136     ("none", EventFilter::empty()),
137     ("all", EventFilter::all()),
138     ("default", EventFilter::DEFAULT),
139     ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
140     ("query-provider", EventFilter::QUERY_PROVIDERS),
141     ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
142     ("query-blocked", EventFilter::QUERY_BLOCKED),
143     ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
144     ("query-keys", EventFilter::QUERY_KEYS),
145 ];
146
147 /// Something that uniquely identifies a query invocation.
148 pub struct QueryInvocationId(pub u32);
149
150 /// A reference to the SelfProfiler. It can be cloned and sent across thread
151 /// boundaries at will.
152 #[derive(Clone)]
153 pub struct SelfProfilerRef {
154     // This field is `None` if self-profiling is disabled for the current
155     // compilation session.
156     profiler: Option<Arc<SelfProfiler>>,
157
158     // We store the filter mask directly in the reference because that doesn't
159     // cost anything and allows for filtering with checking if the profiler is
160     // actually enabled.
161     event_filter_mask: EventFilter,
162
163     // Print verbose generic activities to stdout
164     print_verbose_generic_activities: bool,
165
166     // Print extra verbose generic activities to stdout
167     print_extra_verbose_generic_activities: bool,
168 }
169
170 impl SelfProfilerRef {
171     pub fn new(
172         profiler: Option<Arc<SelfProfiler>>,
173         print_verbose_generic_activities: bool,
174         print_extra_verbose_generic_activities: bool,
175     ) -> SelfProfilerRef {
176         // If there is no SelfProfiler then the filter mask is set to NONE,
177         // ensuring that nothing ever tries to actually access it.
178         let event_filter_mask =
179             profiler.as_ref().map(|p| p.event_filter_mask).unwrap_or(EventFilter::empty());
180
181         SelfProfilerRef {
182             profiler,
183             event_filter_mask,
184             print_verbose_generic_activities,
185             print_extra_verbose_generic_activities,
186         }
187     }
188
189     // This shim makes sure that calls only get executed if the filter mask
190     // lets them pass. It also contains some trickery to make sure that
191     // code is optimized for non-profiling compilation sessions, i.e. anything
192     // past the filter check is never inlined so it doesn't clutter the fast
193     // path.
194     #[inline(always)]
195     fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
196     where
197         F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
198     {
199         #[inline(never)]
200         fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
201         where
202             F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
203         {
204             let profiler = profiler_ref.profiler.as_ref().unwrap();
205             f(&**profiler)
206         }
207
208         if unlikely!(self.event_filter_mask.contains(event_filter)) {
209             cold_call(self, f)
210         } else {
211             TimingGuard::none()
212         }
213     }
214
215     /// Start profiling a verbose generic activity. Profiling continues until the
216     /// VerboseTimingGuard returned from this call is dropped. In addition to recording
217     /// a measureme event, "verbose" generic activities also print a timing entry to
218     /// stdout if the compiler is invoked with -Ztime or -Ztime-passes.
219     #[inline(always)]
220     pub fn verbose_generic_activity<'a>(
221         &'a self,
222         event_id: &'static str,
223     ) -> VerboseTimingGuard<'a> {
224         VerboseTimingGuard::start(
225             event_id,
226             self.print_verbose_generic_activities,
227             self.generic_activity(event_id),
228         )
229     }
230
231     /// Start profiling a extra verbose generic activity. Profiling continues until the
232     /// VerboseTimingGuard returned from this call is dropped. In addition to recording
233     /// a measureme event, "extra verbose" generic activities also print a timing entry to
234     /// stdout if the compiler is invoked with -Ztime-passes.
235     #[inline(always)]
236     pub fn extra_verbose_generic_activity<'a>(
237         &'a self,
238         event_id: &'a str,
239     ) -> VerboseTimingGuard<'a> {
240         // FIXME: This does not yet emit a measureme event
241         // because callers encode arguments into `event_id`.
242         VerboseTimingGuard::start(
243             event_id,
244             self.print_extra_verbose_generic_activities,
245             TimingGuard::none(),
246         )
247     }
248
249     /// Start profiling a generic activity. Profiling continues until the
250     /// TimingGuard returned from this call is dropped.
251     #[inline(always)]
252     pub fn generic_activity(&self, event_id: &'static str) -> TimingGuard<'_> {
253         self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
254             let event_id = profiler.get_or_alloc_cached_string(event_id);
255             let event_id = EventId::from_label(event_id);
256             TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
257         })
258     }
259
260     /// Start profiling a query provider. Profiling continues until the
261     /// TimingGuard returned from this call is dropped.
262     #[inline(always)]
263     pub fn query_provider(&self) -> TimingGuard<'_> {
264         self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
265             TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
266         })
267     }
268
269     /// Record a query in-memory cache hit.
270     #[inline(always)]
271     pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
272         self.instant_query_event(
273             |profiler| profiler.query_cache_hit_event_kind,
274             query_invocation_id,
275             EventFilter::QUERY_CACHE_HITS,
276         );
277     }
278
279     /// Start profiling a query being blocked on a concurrent execution.
280     /// Profiling continues until the TimingGuard returned from this call is
281     /// dropped.
282     #[inline(always)]
283     pub fn query_blocked(&self) -> TimingGuard<'_> {
284         self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
285             TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
286         })
287     }
288
289     /// Start profiling how long it takes to load a query result from the
290     /// incremental compilation on-disk cache. Profiling continues until the
291     /// TimingGuard returned from this call is dropped.
292     #[inline(always)]
293     pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
294         self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
295             TimingGuard::start(
296                 profiler,
297                 profiler.incremental_load_result_event_kind,
298                 EventId::INVALID,
299             )
300         })
301     }
302
303     #[inline(always)]
304     fn instant_query_event(
305         &self,
306         event_kind: fn(&SelfProfiler) -> StringId,
307         query_invocation_id: QueryInvocationId,
308         event_filter: EventFilter,
309     ) {
310         drop(self.exec(event_filter, |profiler| {
311             let event_id = StringId::new_virtual(query_invocation_id.0);
312             let thread_id = std::thread::current().id().as_u64() as u32;
313
314             profiler.profiler.record_instant_event(
315                 event_kind(profiler),
316                 EventId::from_virtual(event_id),
317                 thread_id,
318             );
319
320             TimingGuard::none()
321         }));
322     }
323
324     pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
325         if let Some(profiler) = &self.profiler {
326             f(&profiler)
327         }
328     }
329
330     #[inline]
331     pub fn enabled(&self) -> bool {
332         self.profiler.is_some()
333     }
334 }
335
336 pub struct SelfProfiler {
337     profiler: Profiler,
338     event_filter_mask: EventFilter,
339
340     string_cache: RwLock<FxHashMap<&'static str, StringId>>,
341
342     query_event_kind: StringId,
343     generic_activity_event_kind: StringId,
344     incremental_load_result_event_kind: StringId,
345     query_blocked_event_kind: StringId,
346     query_cache_hit_event_kind: StringId,
347 }
348
349 impl SelfProfiler {
350     pub fn new(
351         output_directory: &Path,
352         crate_name: Option<&str>,
353         event_filters: &Option<Vec<String>>,
354     ) -> Result<SelfProfiler, Box<dyn Error>> {
355         fs::create_dir_all(output_directory)?;
356
357         let crate_name = crate_name.unwrap_or("unknown-crate");
358         let filename = format!("{}-{}.rustc_profile", crate_name, process::id());
359         let path = output_directory.join(&filename);
360         let profiler = Profiler::new(&path)?;
361
362         let query_event_kind = profiler.alloc_string("Query");
363         let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
364         let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
365         let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
366         let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
367
368         let mut event_filter_mask = EventFilter::empty();
369
370         if let Some(ref event_filters) = *event_filters {
371             let mut unknown_events = vec![];
372             for item in event_filters {
373                 if let Some(&(_, mask)) =
374                     EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
375                 {
376                     event_filter_mask |= mask;
377                 } else {
378                     unknown_events.push(item.clone());
379                 }
380             }
381
382             // Warn about any unknown event names
383             if unknown_events.len() > 0 {
384                 unknown_events.sort();
385                 unknown_events.dedup();
386
387                 warn!(
388                     "Unknown self-profiler events specified: {}. Available options are: {}.",
389                     unknown_events.join(", "),
390                     EVENT_FILTERS_BY_NAME
391                         .iter()
392                         .map(|&(name, _)| name.to_string())
393                         .collect::<Vec<_>>()
394                         .join(", ")
395                 );
396             }
397         } else {
398             event_filter_mask = EventFilter::DEFAULT;
399         }
400
401         Ok(SelfProfiler {
402             profiler,
403             event_filter_mask,
404             string_cache: RwLock::new(FxHashMap::default()),
405             query_event_kind,
406             generic_activity_event_kind,
407             incremental_load_result_event_kind,
408             query_blocked_event_kind,
409             query_cache_hit_event_kind,
410         })
411     }
412
413     /// Allocates a new string in the profiling data. Does not do any caching
414     /// or deduplication.
415     pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
416         self.profiler.alloc_string(s)
417     }
418
419     /// Gets a `StringId` for the given string. This method makes sure that
420     /// any strings going through it will only be allocated once in the
421     /// profiling data.
422     pub fn get_or_alloc_cached_string(&self, s: &'static str) -> StringId {
423         // Only acquire a read-lock first since we assume that the string is
424         // already present in the common case.
425         {
426             let string_cache = self.string_cache.read();
427
428             if let Some(&id) = string_cache.get(s) {
429                 return id;
430             }
431         }
432
433         let mut string_cache = self.string_cache.write();
434         // Check if the string has already been added in the small time window
435         // between dropping the read lock and acquiring the write lock.
436         *string_cache.entry(s).or_insert_with(|| self.profiler.alloc_string(s))
437     }
438
439     pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
440         let from = StringId::new_virtual(from.0);
441         self.profiler.map_virtual_to_concrete_string(from, to);
442     }
443
444     pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
445     where
446         I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
447     {
448         let from = from.map(|qid| StringId::new_virtual(qid.0));
449         self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
450     }
451
452     pub fn query_key_recording_enabled(&self) -> bool {
453         self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
454     }
455
456     pub fn event_id_builder(&self) -> EventIdBuilder<'_, SerializationSink> {
457         EventIdBuilder::new(&self.profiler)
458     }
459 }
460
461 #[must_use]
462 pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a, SerializationSink>>);
463
464 impl<'a> TimingGuard<'a> {
465     #[inline]
466     pub fn start(
467         profiler: &'a SelfProfiler,
468         event_kind: StringId,
469         event_id: EventId,
470     ) -> TimingGuard<'a> {
471         let thread_id = std::thread::current().id().as_u64() as u32;
472         let raw_profiler = &profiler.profiler;
473         let timing_guard =
474             raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
475         TimingGuard(Some(timing_guard))
476     }
477
478     #[inline]
479     pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
480         if let Some(guard) = self.0 {
481             let event_id = StringId::new_virtual(query_invocation_id.0);
482             let event_id = EventId::from_virtual(event_id);
483             guard.finish_with_override_event_id(event_id);
484         }
485     }
486
487     #[inline]
488     pub fn none() -> TimingGuard<'a> {
489         TimingGuard(None)
490     }
491
492     #[inline(always)]
493     pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
494         let _timer = self;
495         f()
496     }
497 }
498
499 #[must_use]
500 pub struct VerboseTimingGuard<'a> {
501     event_id: &'a str,
502     start: Option<Instant>,
503     _guard: TimingGuard<'a>,
504 }
505
506 impl<'a> VerboseTimingGuard<'a> {
507     pub fn start(event_id: &'a str, verbose: bool, _guard: TimingGuard<'a>) -> Self {
508         VerboseTimingGuard {
509             event_id,
510             _guard,
511             start: if unlikely!(verbose) { Some(Instant::now()) } else { None },
512         }
513     }
514
515     #[inline(always)]
516     pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
517         let _timer = self;
518         f()
519     }
520 }
521
522 impl Drop for VerboseTimingGuard<'_> {
523     fn drop(&mut self) {
524         self.start.map(|start| print_time_passes_entry(true, self.event_id, start.elapsed()));
525     }
526 }
527
528 pub fn print_time_passes_entry(do_it: bool, what: &str, dur: Duration) {
529     if !do_it {
530         return;
531     }
532
533     let mem_string = match get_resident() {
534         Some(n) => {
535             let mb = n as f64 / 1_000_000.0;
536             format!("; rss: {}MB", mb.round() as usize)
537         }
538         None => String::new(),
539     };
540     println!("time: {}{}\t{}", duration_to_secs_str(dur), mem_string, what);
541 }
542
543 // Hack up our own formatting for the duration to make it easier for scripts
544 // to parse (always use the same number of decimal places and the same unit).
545 pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
546     const NANOS_PER_SEC: f64 = 1_000_000_000.0;
547     let secs = dur.as_secs() as f64 + dur.subsec_nanos() as f64 / NANOS_PER_SEC;
548
549     format!("{:.3}", secs)
550 }
551
552 // Memory reporting
553 #[cfg(unix)]
554 fn get_resident() -> Option<usize> {
555     let field = 1;
556     let contents = fs::read("/proc/self/statm").ok()?;
557     let contents = String::from_utf8(contents).ok()?;
558     let s = contents.split_whitespace().nth(field)?;
559     let npages = s.parse::<usize>().ok()?;
560     Some(npages * 4096)
561 }
562
563 #[cfg(windows)]
564 fn get_resident() -> Option<usize> {
565     use std::mem::{self, MaybeUninit};
566     use winapi::shared::minwindef::DWORD;
567     use winapi::um::processthreadsapi::GetCurrentProcess;
568     use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
569
570     let mut pmc = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
571     match unsafe {
572         GetProcessMemoryInfo(GetCurrentProcess(), pmc.as_mut_ptr(), mem::size_of_val(&pmc) as DWORD)
573     } {
574         0 => None,
575         _ => {
576             let pmc = unsafe { pmc.assume_init() };
577             Some(pmc.WorkingSetSize as usize)
578         }
579     }
580 }