]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_data_structures/src/profiling.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / compiler / rustc_data_structures / src / profiling.rs
CommitLineData
dfeec247
XL
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
74b04a01 84use crate::cold_path;
dfeec247
XL
85use crate::fx::FxHashMap;
86
74b04a01
XL
87use std::borrow::Borrow;
88use std::collections::hash_map::Entry;
89use std::convert::Into;
48663c56 90use std::error::Error;
dc9dc135 91use std::fs;
dc9dc135 92use std::path::Path;
532ac7d7 93use std::process;
e74abb32 94use std::sync::Arc;
dfeec247 95use std::time::{Duration, Instant};
b7449926 96
136023e0
XL
97pub use measureme::EventId;
98use measureme::{EventIdBuilder, Profiler, SerializableString, StringId};
dfeec247 99use parking_lot::RwLock;
04454e1e 100use smallvec::SmallVec;
48663c56 101
60c5eb7d 102bitflags::bitflags! {
48663c56 103 struct EventFilter: u32 {
136023e0
XL
104 const GENERIC_ACTIVITIES = 1 << 0;
105 const QUERY_PROVIDERS = 1 << 1;
106 const QUERY_CACHE_HITS = 1 << 2;
107 const QUERY_BLOCKED = 1 << 3;
108 const INCR_CACHE_LOADS = 1 << 4;
48663c56 109
136023e0
XL
110 const QUERY_KEYS = 1 << 5;
111 const FUNCTION_ARGS = 1 << 6;
112 const LLVM = 1 << 7;
113 const INCR_RESULT_HASHING = 1 << 8;
3c0e092e 114 const ARTIFACT_SIZES = 1 << 9;
dfeec247 115
48663c56
XL
116 const DEFAULT = Self::GENERIC_ACTIVITIES.bits |
117 Self::QUERY_PROVIDERS.bits |
118 Self::QUERY_BLOCKED.bits |
136023e0 119 Self::INCR_CACHE_LOADS.bits |
3c0e092e
XL
120 Self::INCR_RESULT_HASHING.bits |
121 Self::ARTIFACT_SIZES.bits;
74b04a01
XL
122
123 const ARGS = Self::QUERY_KEYS.bits | Self::FUNCTION_ARGS.bits;
9fa01778
XL
124 }
125}
b7449926 126
136023e0 127// keep this in sync with the `-Z self-profile-events` help message in rustc_session/options.rs
48663c56 128const EVENT_FILTERS_BY_NAME: &[(&str, EventFilter)] = &[
dfeec247
XL
129 ("none", EventFilter::empty()),
130 ("all", EventFilter::all()),
131 ("default", EventFilter::DEFAULT),
48663c56
XL
132 ("generic-activity", EventFilter::GENERIC_ACTIVITIES),
133 ("query-provider", EventFilter::QUERY_PROVIDERS),
134 ("query-cache-hit", EventFilter::QUERY_CACHE_HITS),
dfeec247 135 ("query-blocked", EventFilter::QUERY_BLOCKED),
48663c56 136 ("incr-cache-load", EventFilter::INCR_CACHE_LOADS),
dfeec247 137 ("query-keys", EventFilter::QUERY_KEYS),
74b04a01
XL
138 ("function-args", EventFilter::FUNCTION_ARGS),
139 ("args", EventFilter::ARGS),
140 ("llvm", EventFilter::LLVM),
136023e0 141 ("incr-result-hashing", EventFilter::INCR_RESULT_HASHING),
3c0e092e 142 ("artifact-sizes", EventFilter::ARTIFACT_SIZES),
48663c56
XL
143];
144
dfeec247
XL
145/// Something that uniquely identifies a query invocation.
146pub struct QueryInvocationId(pub u32);
e74abb32
XL
147
148/// A reference to the SelfProfiler. It can be cloned and sent across thread
149/// boundaries at will.
150#[derive(Clone)]
151pub struct SelfProfilerRef {
152 // This field is `None` if self-profiling is disabled for the current
153 // compilation session.
154 profiler: Option<Arc<SelfProfiler>>,
155
156 // We store the filter mask directly in the reference because that doesn't
157 // cost anything and allows for filtering with checking if the profiler is
158 // actually enabled.
159 event_filter_mask: EventFilter,
dfeec247
XL
160
161 // Print verbose generic activities to stdout
162 print_verbose_generic_activities: bool,
163
164 // Print extra verbose generic activities to stdout
165 print_extra_verbose_generic_activities: bool,
e74abb32
XL
166}
167
168impl SelfProfilerRef {
dfeec247
XL
169 pub fn new(
170 profiler: Option<Arc<SelfProfiler>>,
171 print_verbose_generic_activities: bool,
172 print_extra_verbose_generic_activities: bool,
173 ) -> SelfProfilerRef {
e74abb32
XL
174 // If there is no SelfProfiler then the filter mask is set to NONE,
175 // ensuring that nothing ever tries to actually access it.
dfeec247 176 let event_filter_mask =
5869c6ff 177 profiler.as_ref().map_or(EventFilter::empty(), |p| p.event_filter_mask);
e74abb32
XL
178
179 SelfProfilerRef {
180 profiler,
181 event_filter_mask,
dfeec247
XL
182 print_verbose_generic_activities,
183 print_extra_verbose_generic_activities,
e74abb32
XL
184 }
185 }
186
04454e1e
FG
187 /// This shim makes sure that calls only get executed if the filter mask
188 /// lets them pass. It also contains some trickery to make sure that
189 /// code is optimized for non-profiling compilation sessions, i.e. anything
190 /// past the filter check is never inlined so it doesn't clutter the fast
191 /// path.
e74abb32
XL
192 #[inline(always)]
193 fn exec<F>(&self, event_filter: EventFilter, f: F) -> TimingGuard<'_>
dfeec247
XL
194 where
195 F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
e74abb32
XL
196 {
197 #[inline(never)]
198 fn cold_call<F>(profiler_ref: &SelfProfilerRef, f: F) -> TimingGuard<'_>
dfeec247
XL
199 where
200 F: for<'a> FnOnce(&'a SelfProfiler) -> TimingGuard<'a>,
e74abb32
XL
201 {
202 let profiler = profiler_ref.profiler.as_ref().unwrap();
203 f(&**profiler)
204 }
205
206 if unlikely!(self.event_filter_mask.contains(event_filter)) {
207 cold_call(self, f)
208 } else {
209 TimingGuard::none()
210 }
211 }
212
dfeec247
XL
213 /// Start profiling a verbose generic activity. Profiling continues until the
214 /// VerboseTimingGuard returned from this call is dropped. In addition to recording
215 /// a measureme event, "verbose" generic activities also print a timing entry to
216 /// stdout if the compiler is invoked with -Ztime or -Ztime-passes.
dfeec247
XL
217 pub fn verbose_generic_activity<'a>(
218 &'a self,
74b04a01 219 event_label: &'static str,
dfeec247 220 ) -> VerboseTimingGuard<'a> {
74b04a01
XL
221 let message =
222 if self.print_verbose_generic_activities { Some(event_label.to_owned()) } else { None };
223
224 VerboseTimingGuard::start(message, self.generic_activity(event_label))
dfeec247
XL
225 }
226
94222f64 227 /// Start profiling an extra verbose generic activity. Profiling continues until the
dfeec247
XL
228 /// VerboseTimingGuard returned from this call is dropped. In addition to recording
229 /// a measureme event, "extra verbose" generic activities also print a timing entry to
230 /// stdout if the compiler is invoked with -Ztime-passes.
74b04a01 231 pub fn extra_verbose_generic_activity<'a, A>(
dfeec247 232 &'a self,
74b04a01
XL
233 event_label: &'static str,
234 event_arg: A,
235 ) -> VerboseTimingGuard<'a>
236 where
237 A: Borrow<str> + Into<String>,
238 {
239 let message = if self.print_extra_verbose_generic_activities {
240 Some(format!("{}({})", event_label, event_arg.borrow()))
241 } else {
242 None
243 };
244
245 VerboseTimingGuard::start(message, self.generic_activity_with_arg(event_label, event_arg))
246 }
247
248 /// Start profiling a generic activity. Profiling continues until the
249 /// TimingGuard returned from this call is dropped.
250 #[inline(always)]
251 pub fn generic_activity(&self, event_label: &'static str) -> TimingGuard<'_> {
252 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
253 let event_label = profiler.get_or_alloc_cached_string(event_label);
254 let event_id = EventId::from_label(event_label);
255 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
256 })
dfeec247
XL
257 }
258
136023e0
XL
259 /// Start profiling with some event filter for a given event. Profiling continues until the
260 /// TimingGuard returned from this call is dropped.
261 #[inline(always)]
262 pub fn generic_activity_with_event_id(&self, event_id: EventId) -> TimingGuard<'_> {
263 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
264 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
265 })
266 }
267
e74abb32
XL
268 /// Start profiling a generic activity. Profiling continues until the
269 /// TimingGuard returned from this call is dropped.
270 #[inline(always)]
74b04a01
XL
271 pub fn generic_activity_with_arg<A>(
272 &self,
273 event_label: &'static str,
274 event_arg: A,
275 ) -> TimingGuard<'_>
276 where
277 A: Borrow<str> + Into<String>,
278 {
e74abb32 279 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
74b04a01
XL
280 let builder = EventIdBuilder::new(&profiler.profiler);
281 let event_label = profiler.get_or_alloc_cached_string(event_label);
282 let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
283 let event_arg = profiler.get_or_alloc_cached_string(event_arg);
284 builder.from_label_and_arg(event_label, event_arg)
285 } else {
286 builder.from_label(event_label)
287 };
dfeec247 288 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
e74abb32
XL
289 })
290 }
291
04454e1e
FG
292 /// Start profiling a generic activity, allowing costly arguments to be recorded. Profiling
293 /// continues until the `TimingGuard` returned from this call is dropped.
294 ///
295 /// If the arguments to a generic activity are cheap to create, use `generic_activity_with_arg`
296 /// or `generic_activity_with_args` for their simpler API. However, if they are costly or
297 /// require allocation in sufficiently hot contexts, then this allows for a closure to be called
298 /// only when arguments were asked to be recorded via `-Z self-profile-events=args`.
299 ///
300 /// In this case, the closure will be passed a `&mut EventArgRecorder`, to help with recording
301 /// one or many arguments within the generic activity being profiled, by calling its
302 /// `record_arg` method for example.
303 ///
304 /// This `EventArgRecorder` may implement more specific traits from other rustc crates, e.g. for
305 /// richer handling of rustc-specific argument types, while keeping this single entry-point API
306 /// for recording arguments.
307 ///
308 /// Note: recording at least one argument is *required* for the self-profiler to create the
309 /// `TimingGuard`. A panic will be triggered if that doesn't happen. This function exists
310 /// explicitly to record arguments, so it fails loudly when there are none to record.
311 ///
312 #[inline(always)]
313 pub fn generic_activity_with_arg_recorder<F>(
314 &self,
315 event_label: &'static str,
316 mut f: F,
317 ) -> TimingGuard<'_>
318 where
319 F: FnMut(&mut EventArgRecorder<'_>),
320 {
321 // Ensure this event will only be recorded when self-profiling is turned on.
322 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
323 let builder = EventIdBuilder::new(&profiler.profiler);
324 let event_label = profiler.get_or_alloc_cached_string(event_label);
325
326 // Ensure the closure to create event arguments will only be called when argument
327 // recording is turned on.
328 let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
329 // Set up the builder and call the user-provided closure to record potentially
330 // costly event arguments.
331 let mut recorder = EventArgRecorder { profiler, args: SmallVec::new() };
332 f(&mut recorder);
333
334 // It is expected that the closure will record at least one argument. If that
335 // doesn't happen, it's a bug: we've been explicitly called in order to record
336 // arguments, so we fail loudly when there are none to record.
337 if recorder.args.is_empty() {
338 panic!(
339 "The closure passed to `generic_activity_with_arg_recorder` needs to \
340 record at least one argument"
341 );
342 }
343
344 builder.from_label_and_args(event_label, &recorder.args)
345 } else {
346 builder.from_label(event_label)
347 };
348 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
349 })
350 }
351
3c0e092e
XL
352 /// Record the size of an artifact that the compiler produces
353 ///
354 /// `artifact_kind` is the class of artifact (e.g., query_cache, object_file, etc.)
355 /// `artifact_name` is an identifier to the specific artifact being stored (usually a filename)
356 #[inline(always)]
357 pub fn artifact_size<A>(&self, artifact_kind: &str, artifact_name: A, size: u64)
358 where
359 A: Borrow<str> + Into<String>,
360 {
361 drop(self.exec(EventFilter::ARTIFACT_SIZES, |profiler| {
362 let builder = EventIdBuilder::new(&profiler.profiler);
363 let event_label = profiler.get_or_alloc_cached_string(artifact_kind);
364 let event_arg = profiler.get_or_alloc_cached_string(artifact_name);
365 let event_id = builder.from_label_and_arg(event_label, event_arg);
366 let thread_id = get_thread_id();
367
368 profiler.profiler.record_integer_event(
369 profiler.artifact_size_event_kind,
370 event_id,
371 thread_id,
372 size,
373 );
374
375 TimingGuard::none()
376 }))
377 }
378
fc512014
XL
379 #[inline(always)]
380 pub fn generic_activity_with_args(
381 &self,
382 event_label: &'static str,
383 event_args: &[String],
384 ) -> TimingGuard<'_> {
385 self.exec(EventFilter::GENERIC_ACTIVITIES, |profiler| {
386 let builder = EventIdBuilder::new(&profiler.profiler);
387 let event_label = profiler.get_or_alloc_cached_string(event_label);
388 let event_id = if profiler.event_filter_mask.contains(EventFilter::FUNCTION_ARGS) {
389 let event_args: Vec<_> = event_args
390 .iter()
391 .map(|s| profiler.get_or_alloc_cached_string(&s[..]))
392 .collect();
393 builder.from_label_and_args(event_label, &event_args)
394 } else {
395 builder.from_label(event_label)
396 };
397 TimingGuard::start(profiler, profiler.generic_activity_event_kind, event_id)
398 })
399 }
400
e74abb32
XL
401 /// Start profiling a query provider. Profiling continues until the
402 /// TimingGuard returned from this call is dropped.
403 #[inline(always)]
dfeec247 404 pub fn query_provider(&self) -> TimingGuard<'_> {
e74abb32 405 self.exec(EventFilter::QUERY_PROVIDERS, |profiler| {
dfeec247 406 TimingGuard::start(profiler, profiler.query_event_kind, EventId::INVALID)
e74abb32
XL
407 })
408 }
409
410 /// Record a query in-memory cache hit.
411 #[inline(always)]
dfeec247 412 pub fn query_cache_hit(&self, query_invocation_id: QueryInvocationId) {
60c5eb7d 413 self.instant_query_event(
e74abb32 414 |profiler| profiler.query_cache_hit_event_kind,
dfeec247 415 query_invocation_id,
e74abb32 416 EventFilter::QUERY_CACHE_HITS,
e74abb32
XL
417 );
418 }
419
420 /// Start profiling a query being blocked on a concurrent execution.
421 /// Profiling continues until the TimingGuard returned from this call is
422 /// dropped.
423 #[inline(always)]
dfeec247 424 pub fn query_blocked(&self) -> TimingGuard<'_> {
e74abb32 425 self.exec(EventFilter::QUERY_BLOCKED, |profiler| {
dfeec247 426 TimingGuard::start(profiler, profiler.query_blocked_event_kind, EventId::INVALID)
e74abb32
XL
427 })
428 }
429
430 /// Start profiling how long it takes to load a query result from the
431 /// incremental compilation on-disk cache. Profiling continues until the
432 /// TimingGuard returned from this call is dropped.
433 #[inline(always)]
dfeec247 434 pub fn incr_cache_loading(&self) -> TimingGuard<'_> {
e74abb32 435 self.exec(EventFilter::INCR_CACHE_LOADS, |profiler| {
e74abb32
XL
436 TimingGuard::start(
437 profiler,
438 profiler.incremental_load_result_event_kind,
dfeec247 439 EventId::INVALID,
e74abb32
XL
440 )
441 })
442 }
443
136023e0
XL
444 /// Start profiling how long it takes to hash query results for incremental compilation.
445 /// Profiling continues until the TimingGuard returned from this call is dropped.
446 #[inline(always)]
447 pub fn incr_result_hashing(&self) -> TimingGuard<'_> {
448 self.exec(EventFilter::INCR_RESULT_HASHING, |profiler| {
449 TimingGuard::start(
450 profiler,
451 profiler.incremental_result_hashing_event_kind,
452 EventId::INVALID,
453 )
454 })
455 }
456
e74abb32 457 #[inline(always)]
60c5eb7d 458 fn instant_query_event(
e74abb32
XL
459 &self,
460 event_kind: fn(&SelfProfiler) -> StringId,
dfeec247 461 query_invocation_id: QueryInvocationId,
e74abb32 462 event_filter: EventFilter,
e74abb32
XL
463 ) {
464 drop(self.exec(event_filter, |profiler| {
dfeec247 465 let event_id = StringId::new_virtual(query_invocation_id.0);
3c0e092e 466 let thread_id = get_thread_id();
e74abb32 467
60c5eb7d 468 profiler.profiler.record_instant_event(
e74abb32 469 event_kind(profiler),
dfeec247 470 EventId::from_virtual(event_id),
e74abb32 471 thread_id,
e74abb32
XL
472 );
473
474 TimingGuard::none()
475 }));
476 }
60c5eb7d 477
dfeec247 478 pub fn with_profiler(&self, f: impl FnOnce(&SelfProfiler)) {
60c5eb7d
XL
479 if let Some(profiler) = &self.profiler {
480 f(&profiler)
481 }
482 }
dfeec247 483
136023e0
XL
484 /// Gets a `StringId` for the given string. This method makes sure that
485 /// any strings going through it will only be allocated once in the
486 /// profiling data.
487 /// Returns `None` if the self-profiling is not enabled.
488 pub fn get_or_alloc_cached_string(&self, s: &str) -> Option<StringId> {
489 self.profiler.as_ref().map(|p| p.get_or_alloc_cached_string(s))
490 }
491
dfeec247
XL
492 #[inline]
493 pub fn enabled(&self) -> bool {
494 self.profiler.is_some()
495 }
74b04a01
XL
496
497 #[inline]
498 pub fn llvm_recording_enabled(&self) -> bool {
499 self.event_filter_mask.contains(EventFilter::LLVM)
500 }
501 #[inline]
502 pub fn get_self_profiler(&self) -> Option<Arc<SelfProfiler>> {
503 self.profiler.clone()
504 }
e74abb32
XL
505}
506
04454e1e
FG
507/// A helper for recording costly arguments to self-profiling events. Used with
508/// `SelfProfilerRef::generic_activity_with_arg_recorder`.
509pub struct EventArgRecorder<'p> {
510 /// The `SelfProfiler` used to intern the event arguments that users will ask to record.
511 profiler: &'p SelfProfiler,
512
513 /// The interned event arguments to be recorded in the generic activity event.
514 ///
515 /// The most common case, when actually recording event arguments, is to have one argument. Then
516 /// followed by recording two, in a couple places.
517 args: SmallVec<[StringId; 2]>,
518}
519
520impl EventArgRecorder<'_> {
521 /// Records a single argument within the current generic activity being profiled.
522 ///
523 /// Note: when self-profiling with costly event arguments, at least one argument
524 /// needs to be recorded. A panic will be triggered if that doesn't happen.
525 pub fn record_arg<A>(&mut self, event_arg: A)
526 where
527 A: Borrow<str> + Into<String>,
528 {
529 let event_arg = self.profiler.get_or_alloc_cached_string(event_arg);
530 self.args.push(event_arg);
531 }
532}
533
532ac7d7 534pub struct SelfProfiler {
48663c56
XL
535 profiler: Profiler,
536 event_filter_mask: EventFilter,
dfeec247 537
74b04a01 538 string_cache: RwLock<FxHashMap<String, StringId>>,
dfeec247 539
48663c56
XL
540 query_event_kind: StringId,
541 generic_activity_event_kind: StringId,
542 incremental_load_result_event_kind: StringId,
136023e0 543 incremental_result_hashing_event_kind: StringId,
48663c56
XL
544 query_blocked_event_kind: StringId,
545 query_cache_hit_event_kind: StringId,
3c0e092e 546 artifact_size_event_kind: StringId,
b7449926
XL
547}
548
549impl SelfProfiler {
dc9dc135
XL
550 pub fn new(
551 output_directory: &Path,
552 crate_name: Option<&str>,
dfeec247 553 event_filters: &Option<Vec<String>>,
29967ef6 554 ) -> Result<SelfProfiler, Box<dyn Error + Send + Sync>> {
dc9dc135
XL
555 fs::create_dir_all(output_directory)?;
556
557 let crate_name = crate_name.unwrap_or("unknown-crate");
558 let filename = format!("{}-{}.rustc_profile", crate_name, process::id());
559 let path = output_directory.join(&filename);
560 let profiler = Profiler::new(&path)?;
48663c56
XL
561
562 let query_event_kind = profiler.alloc_string("Query");
563 let generic_activity_event_kind = profiler.alloc_string("GenericActivity");
564 let incremental_load_result_event_kind = profiler.alloc_string("IncrementalLoadResult");
136023e0
XL
565 let incremental_result_hashing_event_kind =
566 profiler.alloc_string("IncrementalResultHashing");
48663c56
XL
567 let query_blocked_event_kind = profiler.alloc_string("QueryBlocked");
568 let query_cache_hit_event_kind = profiler.alloc_string("QueryCacheHit");
3c0e092e 569 let artifact_size_event_kind = profiler.alloc_string("ArtifactSize");
48663c56
XL
570
571 let mut event_filter_mask = EventFilter::empty();
572
573 if let Some(ref event_filters) = *event_filters {
574 let mut unknown_events = vec![];
575 for item in event_filters {
dfeec247
XL
576 if let Some(&(_, mask)) =
577 EVENT_FILTERS_BY_NAME.iter().find(|&(name, _)| name == item)
578 {
48663c56
XL
579 event_filter_mask |= mask;
580 } else {
581 unknown_events.push(item.clone());
582 }
583 }
584
585 // Warn about any unknown event names
74b04a01 586 if !unknown_events.is_empty() {
48663c56
XL
587 unknown_events.sort();
588 unknown_events.dedup();
589
dfeec247
XL
590 warn!(
591 "Unknown self-profiler events specified: {}. Available options are: {}.",
48663c56 592 unknown_events.join(", "),
dfeec247
XL
593 EVENT_FILTERS_BY_NAME
594 .iter()
595 .map(|&(name, _)| name.to_string())
596 .collect::<Vec<_>>()
597 .join(", ")
598 );
48663c56
XL
599 }
600 } else {
601 event_filter_mask = EventFilter::DEFAULT;
602 }
603
604 Ok(SelfProfiler {
605 profiler,
606 event_filter_mask,
dfeec247 607 string_cache: RwLock::new(FxHashMap::default()),
48663c56
XL
608 query_event_kind,
609 generic_activity_event_kind,
610 incremental_load_result_event_kind,
136023e0 611 incremental_result_hashing_event_kind,
48663c56
XL
612 query_blocked_event_kind,
613 query_cache_hit_event_kind,
3c0e092e 614 artifact_size_event_kind,
48663c56
XL
615 })
616 }
617
dfeec247
XL
618 /// Allocates a new string in the profiling data. Does not do any caching
619 /// or deduplication.
620 pub fn alloc_string<STR: SerializableString + ?Sized>(&self, s: &STR) -> StringId {
621 self.profiler.alloc_string(s)
622 }
623
624 /// Gets a `StringId` for the given string. This method makes sure that
625 /// any strings going through it will only be allocated once in the
626 /// profiling data.
74b04a01
XL
627 pub fn get_or_alloc_cached_string<A>(&self, s: A) -> StringId
628 where
629 A: Borrow<str> + Into<String>,
630 {
dfeec247
XL
631 // Only acquire a read-lock first since we assume that the string is
632 // already present in the common case.
633 {
634 let string_cache = self.string_cache.read();
635
74b04a01 636 if let Some(&id) = string_cache.get(s.borrow()) {
dfeec247
XL
637 return id;
638 }
639 }
640
641 let mut string_cache = self.string_cache.write();
642 // Check if the string has already been added in the small time window
643 // between dropping the read lock and acquiring the write lock.
74b04a01
XL
644 match string_cache.entry(s.into()) {
645 Entry::Occupied(e) => *e.get(),
646 Entry::Vacant(e) => {
647 let string_id = self.profiler.alloc_string(&e.key()[..]);
648 *e.insert(string_id)
649 }
650 }
dfeec247
XL
651 }
652
653 pub fn map_query_invocation_id_to_string(&self, from: QueryInvocationId, to: StringId) {
654 let from = StringId::new_virtual(from.0);
655 self.profiler.map_virtual_to_concrete_string(from, to);
656 }
b7449926 657
dfeec247
XL
658 pub fn bulk_map_query_invocation_id_to_single_string<I>(&self, from: I, to: StringId)
659 where
660 I: Iterator<Item = QueryInvocationId> + ExactSizeIterator,
661 {
662 let from = from.map(|qid| StringId::new_virtual(qid.0));
663 self.profiler.bulk_map_virtual_to_single_concrete_string(from, to);
48663c56
XL
664 }
665
dfeec247
XL
666 pub fn query_key_recording_enabled(&self) -> bool {
667 self.event_filter_mask.contains(EventFilter::QUERY_KEYS)
668 }
669
29967ef6 670 pub fn event_id_builder(&self) -> EventIdBuilder<'_> {
dfeec247 671 EventIdBuilder::new(&self.profiler)
b7449926 672 }
e74abb32 673}
b7449926 674
e74abb32 675#[must_use]
29967ef6 676pub struct TimingGuard<'a>(Option<measureme::TimingGuard<'a>>);
9fa01778 677
e74abb32 678impl<'a> TimingGuard<'a> {
9fa01778 679 #[inline]
e74abb32
XL
680 pub fn start(
681 profiler: &'a SelfProfiler,
682 event_kind: StringId,
dfeec247 683 event_id: EventId,
e74abb32 684 ) -> TimingGuard<'a> {
3c0e092e 685 let thread_id = get_thread_id();
e74abb32 686 let raw_profiler = &profiler.profiler;
dfeec247
XL
687 let timing_guard =
688 raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id);
e74abb32 689 TimingGuard(Some(timing_guard))
9fa01778
XL
690 }
691
dfeec247
XL
692 #[inline]
693 pub fn finish_with_query_invocation_id(self, query_invocation_id: QueryInvocationId) {
694 if let Some(guard) = self.0 {
74b04a01
XL
695 cold_path(|| {
696 let event_id = StringId::new_virtual(query_invocation_id.0);
697 let event_id = EventId::from_virtual(event_id);
698 guard.finish_with_override_event_id(event_id);
699 });
dfeec247
XL
700 }
701 }
702
532ac7d7 703 #[inline]
e74abb32
XL
704 pub fn none() -> TimingGuard<'a> {
705 TimingGuard(None)
b7449926 706 }
dfeec247
XL
707
708 #[inline(always)]
709 pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
710 let _timer = self;
711 f()
712 }
713}
714
715#[must_use]
716pub struct VerboseTimingGuard<'a> {
5869c6ff 717 start_and_message: Option<(Instant, Option<usize>, String)>,
dfeec247
XL
718 _guard: TimingGuard<'a>,
719}
720
721impl<'a> VerboseTimingGuard<'a> {
74b04a01 722 pub fn start(message: Option<String>, _guard: TimingGuard<'a>) -> Self {
5869c6ff
XL
723 VerboseTimingGuard {
724 _guard,
725 start_and_message: message.map(|msg| (Instant::now(), get_resident_set_size(), msg)),
726 }
dfeec247
XL
727 }
728
729 #[inline(always)]
730 pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
731 let _timer = self;
732 f()
733 }
734}
735
736impl Drop for VerboseTimingGuard<'_> {
737 fn drop(&mut self) {
5869c6ff
XL
738 if let Some((start_time, start_rss, ref message)) = self.start_and_message {
739 let end_rss = get_resident_set_size();
04454e1e
FG
740 let dur = start_time.elapsed();
741
742 if should_print_passes(dur, start_rss, end_rss) {
743 print_time_passes_entry(&message, dur, start_rss, end_rss);
744 }
74b04a01 745 }
dfeec247
XL
746 }
747}
748
04454e1e
FG
749fn should_print_passes(dur: Duration, start_rss: Option<usize>, end_rss: Option<usize>) -> bool {
750 if dur.as_millis() > 5 {
751 return true;
752 }
753
754 if let (Some(start_rss), Some(end_rss)) = (start_rss, end_rss) {
755 let change_rss = end_rss.abs_diff(start_rss);
756 if change_rss > 0 {
757 return true;
758 }
759 }
760
761 false
762}
763
5869c6ff
XL
764pub fn print_time_passes_entry(
765 what: &str,
766 dur: Duration,
767 start_rss: Option<usize>,
768 end_rss: Option<usize>,
769) {
770 let rss_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as usize;
771 let rss_change_to_mb = |rss| (rss as f64 / 1_000_000.0).round() as i128;
772
773 let mem_string = match (start_rss, end_rss) {
774 (Some(start_rss), Some(end_rss)) => {
775 let change_rss = end_rss as i128 - start_rss as i128;
776
777 format!(
778 "; rss: {:>4}MB -> {:>4}MB ({:>+5}MB)",
779 rss_to_mb(start_rss),
780 rss_to_mb(end_rss),
781 rss_change_to_mb(change_rss),
782 )
dfeec247 783 }
5869c6ff
XL
784 (Some(start_rss), None) => format!("; rss start: {:>4}MB", rss_to_mb(start_rss)),
785 (None, Some(end_rss)) => format!("; rss end: {:>4}MB", rss_to_mb(end_rss)),
786 (None, None) => String::new(),
dfeec247 787 };
5869c6ff 788
6a06907d 789 eprintln!("time: {:>7}{}\t{}", duration_to_secs_str(dur), mem_string, what);
dfeec247
XL
790}
791
792// Hack up our own formatting for the duration to make it easier for scripts
793// to parse (always use the same number of decimal places and the same unit).
794pub fn duration_to_secs_str(dur: std::time::Duration) -> String {
1b1a35ee 795 format!("{:.3}", dur.as_secs_f64())
dfeec247
XL
796}
797
3c0e092e
XL
798fn get_thread_id() -> u32 {
799 std::thread::current().id().as_u64().get() as u32
800}
801
dfeec247 802// Memory reporting
f9f354fc
XL
803cfg_if! {
804 if #[cfg(windows)] {
5869c6ff 805 pub fn get_resident_set_size() -> Option<usize> {
f9f354fc
XL
806 use std::mem::{self, MaybeUninit};
807 use winapi::shared::minwindef::DWORD;
808 use winapi::um::processthreadsapi::GetCurrentProcess;
809 use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
810
811 let mut pmc = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
812 match unsafe {
813 GetProcessMemoryInfo(GetCurrentProcess(), pmc.as_mut_ptr(), mem::size_of_val(&pmc) as DWORD)
814 } {
815 0 => None,
816 _ => {
817 let pmc = unsafe { pmc.assume_init() };
818 Some(pmc.WorkingSetSize as usize)
819 }
820 }
821 }
822 } else if #[cfg(unix)] {
5869c6ff 823 pub fn get_resident_set_size() -> Option<usize> {
f9f354fc
XL
824 let field = 1;
825 let contents = fs::read("/proc/self/statm").ok()?;
826 let contents = String::from_utf8(contents).ok()?;
827 let s = contents.split_whitespace().nth(field)?;
828 let npages = s.parse::<usize>().ok()?;
829 Some(npages * 4096)
830 }
831 } else {
5869c6ff 832 pub fn get_resident_set_size() -> Option<usize> {
f9f354fc 833 None
dfeec247
XL
834 }
835 }
b7449926 836}