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