Skip to content

Commit 2734b5a

Browse files
authored
Rollup merge of #113723 - khei4:khei4/llvm-stats, r=oli-obk,nikic
Resurrect: rustc_llvm: Add a -Z `print-codegen-stats` option to expose LLVM statistics. This resurrects PR #104000, which has sat idle for a while. And I want to see the effect of stack-move optimizations on LLVM (like https://reviews.llvm.org/D153453) :). I have applied the changes requested by `@oli-obk` and `@nagisa` #104000 (comment) and #104000 (comment) in the latest commits. r? `@oli-obk` ----- LLVM has a neat [statistics](https://llvm.org/docs/ProgrammersManual.html#the-statistic-class-stats-option) feature that tracks how often optimizations kick in. It's very handy for optimization work. Since we expose the LLVM pass timings, I thought it made sense to expose the LLVM statistics too. ----- (Edit: fix broken link (Edit2: fix segmentation fault and use malloc If `rustc` is built with ```toml [llvm] assertions = true ``` Then you can see like ``` rustc +stage1 -Z print-codegen-stats -C opt-level=3 tmp.rs ===-------------------------------------------------------------------------=== ... Statistics Collected ... ===-------------------------------------------------------------------------=== 3 aa - Number of MayAlias results 193 aa - Number of MustAlias results 531 aa - Number of NoAlias results ... ``` And the current default build emits only ``` $ rustc +stage1 -Z print-codegen-stats -C opt-level=3 tmp.rs ===-------------------------------------------------------------------------=== ... Statistics Collected ... ===-------------------------------------------------------------------------=== $ ``` This might be better to emit the message to tell assertion flag necessity, but now I can't find how to do that...
2 parents 20ce7f1 + c7bf20d commit 2734b5a

File tree

10 files changed

+69
-5
lines changed

10 files changed

+69
-5
lines changed

compiler/rustc_codegen_gcc/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,10 @@ impl WriteBackendMethods for GccCodegenBackend {
239239
unimplemented!();
240240
}
241241

242+
fn print_statistics(&self) {
243+
unimplemented!()
244+
}
245+
242246
unsafe fn optimize(_cgcx: &CodegenContext<Self>, _diag_handler: &Handler, module: &ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<(), FatalError> {
243247
module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level));
244248
Ok(())

compiler/rustc_codegen_llvm/src/lib.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ use rustc_span::symbol::Symbol;
4646

4747
use std::any::Any;
4848
use std::ffi::CStr;
49+
use std::io::Write;
4950

5051
mod back {
5152
pub mod archive;
@@ -178,7 +179,28 @@ impl WriteBackendMethods for LlvmCodegenBackend {
178179
type ThinBuffer = back::lto::ThinBuffer;
179180
fn print_pass_timings(&self) {
180181
unsafe {
181-
llvm::LLVMRustPrintPassTimings();
182+
let mut size = 0;
183+
let cstr = llvm::LLVMRustPrintPassTimings(&mut size as *mut usize);
184+
if cstr.is_null() {
185+
println!("failed to get pass timings");
186+
} else {
187+
let timings = std::slice::from_raw_parts(cstr as *const u8, size);
188+
std::io::stdout().write_all(timings).unwrap();
189+
libc::free(cstr as *mut _);
190+
}
191+
}
192+
}
193+
fn print_statistics(&self) {
194+
unsafe {
195+
let mut size = 0;
196+
let cstr = llvm::LLVMRustPrintStatistics(&mut size as *mut usize);
197+
if cstr.is_null() {
198+
println!("failed to get pass stats");
199+
} else {
200+
let stats = std::slice::from_raw_parts(cstr as *const u8, size);
201+
std::io::stdout().write_all(stats).unwrap();
202+
libc::free(cstr as *mut _);
203+
}
182204
}
183205
}
184206
fn run_link(

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1868,7 +1868,10 @@ extern "C" {
18681868
pub fn LLVMRustGetLastError() -> *const c_char;
18691869

18701870
/// Print the pass timings since static dtors aren't picking them up.
1871-
pub fn LLVMRustPrintPassTimings();
1871+
pub fn LLVMRustPrintPassTimings(size: *const size_t) -> *const c_char;
1872+
1873+
/// Print the statistics since static dtors aren't picking them up.
1874+
pub fn LLVMRustPrintStatistics(size: *const size_t) -> *const c_char;
18721875

18731876
pub fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type;
18741877

compiler/rustc_codegen_llvm/src/llvm_util.rs

+4
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ unsafe fn configure_llvm(sess: &Session) {
110110
// Use non-zero `import-instr-limit` multiplier for cold callsites.
111111
add("-import-cold-multiplier=0.1", false);
112112

113+
if sess.print_llvm_stats() {
114+
add("-stats", false);
115+
}
116+
113117
for arg in sess_args {
114118
add(&(*arg), true);
115119
}

compiler/rustc_codegen_ssa/src/back/write.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1945,6 +1945,10 @@ impl<B: ExtraBackendMethods> OngoingCodegen<B> {
19451945
self.backend.print_pass_timings()
19461946
}
19471947

1948+
if sess.print_llvm_stats() {
1949+
self.backend.print_statistics()
1950+
}
1951+
19481952
(
19491953
CodegenResults {
19501954
metadata: self.metadata,

compiler/rustc_codegen_ssa/src/traits/write.rs

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
3535
cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
3636
) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError>;
3737
fn print_pass_timings(&self);
38+
fn print_statistics(&self);
3839
unsafe fn optimize(
3940
cgcx: &CodegenContext<Self>,
4041
diag_handler: &Handler,

compiler/rustc_interface/src/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -715,6 +715,7 @@ fn test_unstable_options_tracking_hash() {
715715
untracked!(perf_stats, true);
716716
// `pre_link_arg` is omitted because it just forwards to `pre_link_args`.
717717
untracked!(pre_link_args, vec![String::from("abc"), String::from("def")]);
718+
untracked!(print_codegen_stats, true);
718719
untracked!(print_llvm_passes, true);
719720
untracked!(print_mono_items, Some(String::from("abc")));
720721
untracked!(print_type_sizes, true);

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

+21-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "LLVMWrapper.h"
2+
#include "llvm/ADT/Statistic.h"
23
#include "llvm/IR/DebugInfoMetadata.h"
34
#include "llvm/IR/DiagnosticHandler.h"
45
#include "llvm/IR/DiagnosticInfo.h"
@@ -111,9 +112,26 @@ extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
111112
unwrap(M)->setTargetTriple(Triple::normalize(Triple));
112113
}
113114

114-
extern "C" void LLVMRustPrintPassTimings() {
115-
raw_fd_ostream OS(2, false); // stderr.
116-
TimerGroup::printAll(OS);
115+
extern "C" const char *LLVMRustPrintPassTimings(size_t *Len) {
116+
std::string buf;
117+
raw_string_ostream SS(buf);
118+
TimerGroup::printAll(SS);
119+
SS.flush();
120+
*Len = buf.length();
121+
char *CStr = (char *)malloc(*Len);
122+
memcpy(CStr, buf.c_str(), *Len);
123+
return CStr;
124+
}
125+
126+
extern "C" const char *LLVMRustPrintStatistics(size_t *Len) {
127+
std::string buf;
128+
raw_string_ostream SS(buf);
129+
llvm::PrintStatistics(SS);
130+
SS.flush();
131+
*Len = buf.length();
132+
char *CStr = (char *)malloc(*Len);
133+
memcpy(CStr, buf.c_str(), *Len);
134+
return CStr;
117135
}
118136

119137
extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M, const char *Name,

compiler/rustc_session/src/options.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1668,6 +1668,9 @@ options! {
16681668
"use a more precise version of drop elaboration for matches on enums (default: yes). \
16691669
This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
16701670
See #77382 and #74551."),
1671+
#[rustc_lint_opt_deny_field_access("use `Session::print_codegen_stats` instead of this field")]
1672+
print_codegen_stats: bool = (false, parse_bool, [UNTRACKED],
1673+
"print codegen statistics (default: no)"),
16711674
print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
16721675
"make rustc print the total optimization fuel used by a crate"),
16731676
print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],

compiler/rustc_session/src/session.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1057,6 +1057,10 @@ impl Session {
10571057
self.opts.unstable_opts.verbose
10581058
}
10591059

1060+
pub fn print_llvm_stats(&self) -> bool {
1061+
self.opts.unstable_opts.print_codegen_stats
1062+
}
1063+
10601064
pub fn verify_llvm_ir(&self) -> bool {
10611065
self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
10621066
}

0 commit comments

Comments
 (0)