Skip to main content

bootstrap/core/build_steps/
perf.rs

1use std::env::consts::EXE_EXTENSION;
2use std::fmt::{Display, Formatter};
3use std::path::PathBuf;
4
5use crate::core::build_steps::compile::Sysroot;
6use crate::core::build_steps::tool::{RustcPerf, Rustdoc};
7use crate::core::builder::Builder;
8use crate::core::config::DebuginfoLevel;
9use crate::utils::exec::{BootstrapCommand, command};
10
11#[derive(Debug, Clone, clap::Parser)]
12pub struct PerfArgs {
13    #[clap(subcommand)]
14    cmd: PerfCommand,
15}
16
17#[derive(Debug, Clone, clap::Parser)]
18enum PerfCommand {
19    /// Run `profile_local eprintln`.
20    /// This executes the compiler on the given benchmarks and stores its stderr output.
21    Eprintln {
22        #[clap(flatten)]
23        opts: SharedOpts,
24    },
25    /// Run `profile_local samply`
26    /// This executes the compiler on the given benchmarks and profiles it with `samply`.
27    /// You need to install `samply`, e.g. using `cargo install --locked samply`.
28    Samply {
29        #[clap(flatten)]
30        opts: SharedOpts,
31    },
32    /// Run `profile_local cachegrind`.
33    /// This executes the compiler on the given benchmarks under `Cachegrind`.
34    Cachegrind {
35        #[clap(flatten)]
36        opts: SharedOpts,
37    },
38    /// Run compile benchmarks with a locally built compiler.
39    Benchmark {
40        /// Identifier to associate benchmark results with
41        #[clap(name = "benchmark-id")]
42        id: String,
43
44        #[clap(flatten)]
45        opts: SharedOpts,
46    },
47    /// Compare the results of two previously executed benchmark runs.
48    Compare {
49        /// The name of the base artifact to be compared.
50        base: String,
51
52        /// The name of the modified artifact to be compared.
53        modified: String,
54
55        #[clap(long, global = true)]
56        database_path: Option<String>,
57    },
58}
59
60impl PerfCommand {
61    fn shared_opts(&self) -> Option<&SharedOpts> {
62        match self {
63            PerfCommand::Eprintln { opts, .. }
64            | PerfCommand::Samply { opts, .. }
65            | PerfCommand::Cachegrind { opts, .. }
66            | PerfCommand::Benchmark { opts, .. } => Some(opts),
67            PerfCommand::Compare { .. } => None,
68        }
69    }
70}
71
72#[derive(Debug, Clone, clap::Parser)]
73struct SharedOpts {
74    /// Select the benchmarks that you want to run (separated by commas).
75    /// If unspecified, all benchmarks will be executed.
76    #[clap(long, global = true, value_delimiter = ',')]
77    include: Vec<String>,
78
79    /// Select the benchmarks matching a prefix in this comma-separated list that you don't want to run.
80    #[clap(long, global = true, value_delimiter = ',')]
81    exclude: Vec<String>,
82
83    /// Select the scenarios that should be benchmarked.
84    #[clap(
85        long,
86        global = true,
87        value_delimiter = ',',
88        default_value = "Full,IncrFull,IncrUnchanged,IncrPatched"
89    )]
90    scenarios: Vec<Scenario>,
91    /// Select the profiles that should be benchmarked.
92    #[clap(long, global = true, value_delimiter = ',', default_value = "Check,Debug,Opt")]
93    profiles: Vec<Profile>,
94
95    #[clap(long, global = true)]
96    database_path: Option<String>,
97
98    /// Comma-separated list of thread counts for the parallel frontend. Maps directly to the
99    /// `-Zthreads` rustc option. If unspecified, `rustc-perf` uses only 1.
100    #[clap(long, global = true, value_delimiter = ',')]
101    frontend_threads: Vec<usize>,
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, clap::ValueEnum)]
105#[value(rename_all = "PascalCase")]
106pub enum Profile {
107    Check,
108    Debug,
109    Doc,
110    DocJson,
111    Opt,
112    Clippy,
113}
114
115impl Display for Profile {
116    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117        let name = match self {
118            Profile::Check => "Check",
119            Profile::Debug => "Debug",
120            Profile::Doc => "Doc",
121            Profile::DocJson => "DocJson",
122            Profile::Opt => "Opt",
123            Profile::Clippy => "Clippy",
124        };
125        f.write_str(name)
126    }
127}
128
129#[derive(Clone, Copy, Debug, clap::ValueEnum)]
130#[value(rename_all = "PascalCase")]
131pub enum Scenario {
132    Full,
133    IncrFull,
134    IncrUnchanged,
135    IncrPatched,
136}
137
138impl Display for Scenario {
139    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
140        let name = match self {
141            Scenario::Full => "Full",
142            Scenario::IncrFull => "IncrFull",
143            Scenario::IncrUnchanged => "IncrUnchanged",
144            Scenario::IncrPatched => "IncrPatched",
145        };
146        f.write_str(name)
147    }
148}
149
150/// Performs profiling using `rustc-perf` on a built version of the compiler.
151pub fn perf(builder: &Builder<'_>, args: &PerfArgs, trailing_args: &[String]) {
152    let mut cmd = if let Some(ref custom_rustc_perf_path) = builder.rustc_perf_path {
153        builder.info(&format!("using custom rustc_perf at `{}`", custom_rustc_perf_path.display()));
154        let mut cmd = command("cargo");
155        cmd.arg("run");
156        cmd.arg("--release");
157        cmd.args(["--bin", "collector"]);
158        cmd.arg("--");
159        cmd.current_dir(custom_rustc_perf_path);
160        cmd
161    } else {
162        let collector = builder.ensure(RustcPerf {
163            compiler: builder.compiler(0, builder.config.host_target),
164            target: builder.config.host_target,
165        });
166
167        let mut cmd = command(collector.tool_path);
168
169        // We need to set the working directory to `src/tools/rustc-perf`, so that it can find the directory
170        // with compile-time benchmarks.
171        cmd.current_dir(builder.src.join("src/tools/rustc-perf"));
172
173        cmd
174    };
175
176    let rustc_perf_dir = builder.sess.tempdir().join("rustc-perf");
177    let results_dir = rustc_perf_dir.join("results");
178    builder.create_dir(&results_dir);
179
180    let db_path = args
181        .cmd
182        .shared_opts()
183        .and_then(|i| i.database_path.as_ref())
184        .or(if let PerfCommand::Compare { database_path: Some(path), .. } = &args.cmd {
185            Some(path)
186        } else {
187            None
188        })
189        .map(|i| PathBuf::from(i.as_str()))
190        .unwrap_or_else(|| results_dir.join("results.db"));
191
192    let is_profiling = match &args.cmd {
193        PerfCommand::Eprintln { .. }
194        | PerfCommand::Samply { .. }
195        | PerfCommand::Cachegrind { .. } => true,
196        PerfCommand::Benchmark { .. } | PerfCommand::Compare { .. } => false,
197    };
198    if is_profiling && builder.sess.config.rust_debuginfo_level_rustc == DebuginfoLevel::None {
199        builder.info(r#"WARNING: You are compiling rustc without debuginfo, this will make profiling less useful.
200Consider setting `rust.debuginfo-level = 1` in `bootstrap.toml`."#);
201    }
202
203    let prepare_rustc = || {
204        let compiler = builder.compiler(builder.top_stage, builder.config.host_target);
205        builder.std(compiler, builder.config.host_target);
206
207        if let Some(opts) = args.cmd.shared_opts()
208            && opts.profiles.contains(&Profile::Doc)
209        {
210            builder.ensure(Rustdoc { target_compiler: compiler });
211        }
212
213        let sysroot = builder.ensure(Sysroot::new(compiler));
214        let mut rustc = sysroot.clone();
215        rustc.push("bin");
216        rustc.push("rustc");
217        rustc.set_extension(EXE_EXTENSION);
218        rustc
219    };
220
221    match &args.cmd {
222        PerfCommand::Eprintln { opts }
223        | PerfCommand::Samply { opts }
224        | PerfCommand::Cachegrind { opts } => {
225            cmd.arg("profile_local");
226            cmd.arg(match &args.cmd {
227                PerfCommand::Eprintln { .. } => "eprintln",
228                PerfCommand::Samply { .. } => "samply",
229                PerfCommand::Cachegrind { .. } => "cachegrind",
230                _ => unreachable!(),
231            });
232
233            cmd.arg("--out-dir").arg(&results_dir);
234            cmd.arg(prepare_rustc());
235
236            apply_shared_opts(&mut cmd, opts);
237            cmd.args(trailing_args);
238            cmd.run(builder);
239
240            println!("You can find the results at `{}`", results_dir.display());
241        }
242        PerfCommand::Benchmark { id, opts } => {
243            cmd.arg("bench_local");
244            cmd.arg("--db").arg(&db_path);
245            cmd.arg("--id").arg(id);
246            cmd.arg(prepare_rustc());
247
248            apply_shared_opts(&mut cmd, opts);
249            cmd.args(trailing_args);
250            cmd.run(builder);
251        }
252        PerfCommand::Compare { base, modified, database_path: _ } => {
253            cmd.arg("bench_cmp");
254            cmd.arg("--db").arg(&db_path);
255            cmd.arg(base).arg(modified);
256
257            cmd.args(trailing_args);
258            cmd.run(builder);
259        }
260    }
261}
262
263fn apply_shared_opts(cmd: &mut BootstrapCommand, opts: &SharedOpts) {
264    if !opts.include.is_empty() {
265        cmd.arg("--include").arg(opts.include.join(","));
266    }
267    if !opts.exclude.is_empty() {
268        cmd.arg("--exclude").arg(opts.exclude.join(","));
269    }
270    if !opts.profiles.is_empty() {
271        cmd.arg("--profiles")
272            .arg(opts.profiles.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(","));
273    }
274    if !opts.scenarios.is_empty() {
275        cmd.arg("--scenarios")
276            .arg(opts.scenarios.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(","));
277    }
278    if !opts.frontend_threads.is_empty() {
279        cmd.arg("--frontend-threads")
280            .arg(opts.frontend_threads.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(","));
281    }
282}