1 //! # Rust Compiler Self-Profiling
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.
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.
18 //! Events have a few properties:
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.
30 //! ## Event Filtering
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.
39 //! ## `event_id` Assignment
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:
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.
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.
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()`.
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.
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`.
82 //! [mm]: https://github.com/rust-lang/measureme/
85 use crate::fx::FxHashMap;
87 use std::borrow::Borrow;
88 use std::collections::hash_map::Entry;
89 use std::convert::Into;
90 use std::error::Error;
95 use std::time::{Duration, Instant};
97 use measureme::{EventId, EventIdBuilder, SerializableString, StringId};
98 use parking_lot::RwLock;
101 if #[cfg(target_arch = "wasm32")] {
103 if #[cfg(target_os = "wasi")] {
104 type SerializationSink = measureme::FileSerializationSink;
106 type SerializationSink = measureme::ByteVecSink;
112 /// FileSerializationSink is faster on Windows
113 type SerializationSink = measureme::FileSerializationSink;
115 /// MmapSerializatioSink is faster on macOS and Linux
116 type SerializationSink = measureme::MmapSerializationSink;
122 type Profiler = measureme::Profiler<SerializationSink>;
124 #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
125 pub enum ProfileCategory {
135 bitflags::bitflags! {
136 struct EventFilter: u32 {
137 const GENERIC_ACTIVITIES = 1 << 0;
138 const QUERY_PROVIDERS = 1 << 1;
139 const QUERY_CACHE_HITS = 1 << 2;
140 const QUERY_BLOCKED = 1 << 3;
141 const INCR_CACHE_LOADS = 1 << 4;
143 const QUERY_KEYS = 1 << 5;
144 const FUNCTION_ARGS = 1 << 6;
147 const DEFAULT = Self::GENERIC_ACTIVITIES.bits |
148 Self::QUERY_PROVIDERS.bits |
149 Self::QUERY_BLOCKED.bits |
150 Self::INCR_CACHE_LOADS.bits;
152 const ARGS = Self::QUERY_KEYS.bits | Self::FUNCTION_ARGS.bits;
156 // keep this in sync with the `-Z self-profile-events` help message in librustc_session/options.rs
157 const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
158 ("none", EventFilter::empty()),
159 ("all", EventFilter::all()),
160 ("default", EventFilter::DEFAULT),
161 ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
162 ("query-provider", EventFilter::QUERY_PROVIDERS),
163 ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
164 ("query-blocked", EventFilter::QUERY_BLOCKED),
165 ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
166 ("query-keys", EventFilter::QUERY_KEYS),
167 ("function-args", EventFilter::FUNCTION_ARGS),
168 ("args", EventFilter::ARGS),
169 ("llvm", EventFilter::LLVM),
172 /// Something that uniquely identifies a query invocation.
173 pub struct QueryInvocationId(pub u32);
175 /// A reference to the SelfProfiler. It can be cloned and sent across thread
176 /// boundaries at will.
178 pub struct SelfProfilerRef {
179 // This field is `None` if self-profiling is disabled for the current
180 // compilation session.
181 profiler: Option<Arc<SelfProfiler>>,
183 // We store the filter mask directly in the reference because that doesn't
184 // cost anything and allows for filtering with checking if the profiler is
186 event_filter_mask: EventFilter,
188 // Print verbose generic activities to stdout
189 print_verbose_generic_activities: bool,
191 // Print extra verbose generic activities to stdout
192 print_extra_verbose_generic_activities: bool,
195 impl SelfProfilerRef {
197 profiler: Option<Arc<SelfProfiler>>,
198 print_verbose_generic_activities: bool,
199 print_extra_verbose_generic_activities: bool,
200 ) -> SelfProfilerRef {
201 // If there is no SelfProfiler then the filter mask is set to NONE,
202 // ensuring that nothing ever tries to actually access it.
203 let event_filter_mask =
204 profiler.as_ref().map(|p| p.event_filter_mask).unwrap_or(EventFilter::empty());
209 print_verbose_generic_activities,
210 print_extra_verbose_generic_activities,
214 // This shim makes sure that calls only get executed if the filter mask
215 // lets them pass. It also contains some trickery to make sure that
216 // code is optimized for non-profiling compilation sessions, i.e. anything
217 // past the filter check is never inlined so it doesn't clutter the fast
220 fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
222 F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
225 fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
227 F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
229 let profiler = profiler_ref.profiler.as_ref().unwrap();
233 if unlikely!(self.event_filter_mask.contains(event_filter)) {
240 /// Start profiling a verbose generic activity. Profiling continues until the
241 /// VerboseTimingGuard returned from this call is dropped. In addition to recording
242 /// a measureme event, "verbose" generic activities also print a timing entry to
243 /// stdout if the compiler is invoked with -Ztime or -Ztime-passes.
244 pub fn verbose_generic_activity<'a>(
246 event_label: &'static str,
247 ) -> VerboseTimingGuard<'a> {
249 if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None };
251 VerboseTimingGuard::start(message, self.generic_activity(event_label))
254 /// Start profiling a extra verbose generic activity. Profiling continues until the
255 /// VerboseTimingGuard returned from this call is dropped. In addition to recording
256 /// a measureme event, "extra verbose" generic activities also print a timing entry to
257 /// stdout if the compiler is invoked with -Ztime-passes.
258 pub fn extra_verbose_generic_activity<'a, A>(
260 event_label: &'static str,
262 ) -> VerboseTimingGuard<'a>
264 A: Borrow<str> + Into<String>,
266 let message = if self.print_extra_verbose_generic_activities {
267 Some(format!("{}({})", event_label, event_arg.borrow()))
272 VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg))
275 /// Start profiling a generic activity. Profiling continues until the
276 /// TimingGuard returned from this call is dropped.
278 pub fn generic_activity(&self, event_label: &'static str) -> TimingGuard<'_> {
279 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
280 let event_label = profiler.get_or_alloc_cached_string(event_label);
281 let event_id = EventId::from_label(event_label);
282 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
286 /// Start profiling a generic activity. Profiling continues until the
287 /// TimingGuard returned from this call is dropped.
289 pub fn generic_activity_with_arg<A>(
291 event_label: &'static str,
295 A: Borrow<str> + Into<String>,
297 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
298 let builder = EventIdBuilder::new(&profiler.profiler);
299 let event_label = profiler.get_or_alloc_cached_string(event_label);
300 let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
301 let event_arg = profiler.get_or_alloc_cached_string(event_arg);
302 builder.from_label_and_arg(event_label, event_arg)
304 builder.from_label(event_label)
306 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
310 /// Start profiling a query provider. Profiling continues until the
311 /// TimingGuard returned from this call is dropped.
313 pub fn query_provider(&self) -> TimingGuard<'_> {
314 self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
315 TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
319 /// Record a query in-memory cache hit.
321 pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
322 self.instant_query_event(
323 |profiler| profiler.query_cache_hit_event_kind,
325 EventFilter::QUERY_CACHE_HITS,
329 /// Start profiling a query being blocked on a concurrent execution.
330 /// Profiling continues until the TimingGuard returned from this call is
333 pub fn query_blocked(&self) -> TimingGuard<'_> {
334 self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
335 TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
339 /// Start profiling how long it takes to load a query result from the
340 /// incremental compilation on-disk cache. Profiling continues until the
341 /// TimingGuard returned from this call is dropped.
343 pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
344 self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
347 profiler.incremental_load_result_event_kind,
354 fn instant_query_event(
356 event_kind: fn(&SelfProfiler) -> StringId,
357 query_invocation_id: QueryInvocationId,
358 event_filter: EventFilter,
360 drop(self.exec(event_filter, |profiler| {
361 let event_id = StringId::new_virtual(query_invocation_id.0);
362 let thread_id = std::thread::current().id().as_u64().get() as u32;
364 profiler.profiler.record_instant_event(
365 event_kind(profiler),
366 EventId::from_virtual(event_id),
374 pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
375 if let Some(profiler) = &self.profiler {
381 pub fn enabled(&self) -> bool {
382 self.profiler.is_some()
386 pub fn llvm_recording_enabled(&self) -> bool {
387 self.event_filter_mask.contains(EventFilter::LLVM)
390 pub fn get_self_profiler(&self) -> Option<Arc<SelfProfiler>> {
391 self.profiler.clone()
395 pub struct SelfProfiler {
397 event_filter_mask: EventFilter,
399 string_cache: RwLock<FxHashMap<String, StringId>>,
401 query_event_kind: StringId,
402 generic_activity_event_kind: StringId,
403 incremental_load_result_event_kind: StringId,
404 query_blocked_event_kind: StringId,
405 query_cache_hit_event_kind: StringId,
410 output_directory: &Path,
411 crate_name: Option<&str>,
412 event_filters: &Option<Vec<String>>,
413 ) -> Result<SelfProfiler, Box<dyn Error>> {
414 fs::create_dir_all(output_directory)?;
416 let crate_name = crate_name.unwrap_or("unknown-crate");
417 let filename = format!("{}-{}.rustc_profile", crate_name, process::id());
418 let path = output_directory.join(&filename);
419 let profiler = Profiler::new(&path)?;
421 let query_event_kind = profiler.alloc_string("Query");
422 let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
423 let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
424 let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
425 let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
427 let mut event_filter_mask = EventFilter::empty();
429 if let Some(ref event_filters) = *event_filters {
430 let mut unknown_events = vec![];
431 for item in event_filters {
432 if let Some(&(_, mask)) =
433 EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
435 event_filter_mask |= mask;
437 unknown_events.push(item.clone());
441 // Warn about any unknown event names
442 if !unknown_events.is_empty() {
443 unknown_events.sort();
444 unknown_events.dedup();
447 "Unknown self-profiler events specified: {}. Available options are: {}.",
448 unknown_events.join(", "),
449 EVENT_FILTERS_BY_NAME
451 .map(|&(name, _)| name.to_string())
457 event_filter_mask = EventFilter::DEFAULT;
463 string_cache: RwLock::new(FxHashMap::default()),
465 generic_activity_event_kind,
466 incremental_load_result_event_kind,
467 query_blocked_event_kind,
468 query_cache_hit_event_kind,
472 /// Allocates a new string in the profiling data. Does not do any caching
473 /// or deduplication.
474 pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
475 self.profiler.alloc_string(s)
478 /// Gets a `StringId` for the given string. This method makes sure that
479 /// any strings going through it will only be allocated once in the
481 pub fn get_or_alloc_cached_string<A>(&self, s: A) -> StringId
483 A: Borrow<str> + Into<String>,
485 // Only acquire a read-lock first since we assume that the string is
486 // already present in the common case.
488 let string_cache = self.string_cache.read();
490 if let Some(&id) = string_cache.get(s.borrow()) {
495 let mut string_cache = self.string_cache.write();
496 // Check if the string has already been added in the small time window
497 // between dropping the read lock and acquiring the write lock.
498 match string_cache.entry(s.into()) {
499 Entry::Occupied(e) => *e.get(),
500 Entry::Vacant(e) => {
501 let string_id = self.profiler.alloc_string(&e.key()[..]);
507 pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
508 let from = StringId::new_virtual(from.0);
509 self.profiler.map_virtual_to_concrete_string(from, to);
512 pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
514 I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
516 let from = from.map(|qid| StringId::new_virtual(qid.0));
517 self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
520 pub fn query_key_recording_enabled(&self) -> bool {
521 self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
524 pub fn event_id_builder(&self) -> EventIdBuilder<'_, SerializationSink> {
525 EventIdBuilder::new(&self.profiler)
530 pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a, SerializationSink>>);
532 impl<'a> TimingGuard<'a> {
535 profiler: &'a SelfProfiler,
536 event_kind: StringId,
538 ) -> TimingGuard<'a> {
539 let thread_id = std::thread::current().id().as_u64().get() as u32;
540 let raw_profiler = &profiler.profiler;
542 raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
543 TimingGuard(Some(timing_guard))
547 pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
548 if let Some(guard) = self.0 {
550 let event_id = StringId::new_virtual(query_invocation_id.0);
551 let event_id = EventId::from_virtual(event_id);
552 guard.finish_with_override_event_id(event_id);
558 pub fn none() -> TimingGuard<'a> {
563 pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
570 pub struct VerboseTimingGuard<'a> {
571 start_and_message: Option<(Instant, String)>,
572 _guard: TimingGuard<'a>,
575 impl<'a> VerboseTimingGuard<'a> {
576 pub fn start(message: Option<String>, _guard: TimingGuard<'a>) -> Self {
577 VerboseTimingGuard { _guard, start_and_message: message.map(|msg| (Instant::now(), msg)) }
581 pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
587 impl Drop for VerboseTimingGuard<'_> {
589 if let Some((start, ref message)) = self.start_and_message {
590 print_time_passes_entry(true, &message[..], start.elapsed());
595 pub fn print_time_passes_entry(do_it: bool, what: &str, dur: Duration) {
600 let mem_string = match get_resident() {
602 let mb = n as f64 / 1_000_000.0;
603 format!("; rss: {}MB", mb.round() as usize)
605 None => String::new(),
607 println!("time: {}{}\t{}", duration_to_secs_str(dur), mem_string, what);
610 // Hack up our own formatting for the duration to make it easier for scripts
611 // to parse (always use the same number of decimal places and the same unit).
612 pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
613 const NANOS_PER_SEC: f64 = 1_000_000_000.0;
614 let secs = dur.as_secs() as f64 + dur.subsec_nanos() as f64 / NANOS_PER_SEC;
616 format!("{:.3}", secs)
621 if #[cfg(target_arch = "wasm32")] {
622 fn get_resident() -> Option<usize> {
628 fn get_resident() -> Option<usize> {
629 use std::mem::{self, MaybeUninit};
630 use winapi::shared::minwindef::DWORD;
631 use winapi::um::processthreadsapi::GetCurrentProcess;
632 use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
634 let mut pmc = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
636 GetProcessMemoryInfo(GetCurrentProcess(), pmc.as_mut_ptr(), mem::size_of_val(&pmc) as DWORD)
640 let pmc = unsafe { pmc.assume_init() };
641 Some(pmc.WorkingSetSize as usize)
646 fn get_resident() -> Option<usize> {
648 let contents = fs::read("/proc/self/statm").ok()?;
649 let contents = String::from_utf8(contents).ok()?;
650 let s = contents.split_whitespace().nth(field)?;
651 let npages = s.parse::<usize>().ok()?;