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