Skip to content

Commit adfcae2

Browse files
committed
Add rustc option to output LLVM optimization remarks to YAML files
1 parent 8882507 commit adfcae2

File tree

7 files changed

+134
-13
lines changed

7 files changed

+134
-13
lines changed

compiler/rustc_codegen_llvm/src/back/lto.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::back::write::{self, save_temp_bitcode, DiagnosticHandlers};
1+
use crate::back::write::{self, save_temp_bitcode, CodegenDiagnosticsSection, DiagnosticHandlers};
22
use crate::errors::{
33
DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib,
44
};
@@ -302,7 +302,13 @@ fn fat_lto(
302302
// The linking steps below may produce errors and diagnostics within LLVM
303303
// which we'd like to handle and print, so set up our diagnostic handlers
304304
// (which get unregistered when they go out of scope below).
305-
let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
305+
let _handler = DiagnosticHandlers::new(
306+
cgcx,
307+
diag_handler,
308+
llcx,
309+
&module,
310+
CodegenDiagnosticsSection::LTO,
311+
);
306312

307313
// For all other modules we codegened we'll need to link them into our own
308314
// bitcode. All modules were codegened in their own LLVM context, however,

compiler/rustc_codegen_llvm/src/back/write.rs

+36-3
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,13 @@ pub(crate) fn save_temp_bitcode(
268268
}
269269
}
270270

271+
/// In what context is a dignostic handler being attached to a codegen unit?
272+
pub enum CodegenDiagnosticsSection {
273+
Codegen,
274+
Opt,
275+
LTO,
276+
}
277+
271278
pub struct DiagnosticHandlers<'a> {
272279
data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
273280
llcx: &'a llvm::Context,
@@ -279,6 +286,8 @@ impl<'a> DiagnosticHandlers<'a> {
279286
cgcx: &'a CodegenContext<LlvmCodegenBackend>,
280287
handler: &'a Handler,
281288
llcx: &'a llvm::Context,
289+
module: &ModuleCodegen<ModuleLlvm>,
290+
section: CodegenDiagnosticsSection,
282291
) -> Self {
283292
let remark_passes_all: bool;
284293
let remark_passes: Vec<CString>;
@@ -295,6 +304,21 @@ impl<'a> DiagnosticHandlers<'a> {
295304
};
296305
let remark_passes: Vec<*const c_char> =
297306
remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
307+
let remark_file = cgcx
308+
.remark_dir
309+
.as_ref()
310+
.and_then(|dir| dir.to_str())
311+
// Use the .opt.yaml file pattern, which is supported by LLVM's opt-viewer.
312+
.map(|dir| {
313+
let section = match section {
314+
CodegenDiagnosticsSection::Codegen => "codegen",
315+
CodegenDiagnosticsSection::Opt => "opt",
316+
CodegenDiagnosticsSection::LTO => "lto",
317+
};
318+
format!("{dir}/{}.{section}.opt.yaml", module.name)
319+
})
320+
.map(|dir| CString::new(dir).unwrap());
321+
298322
let data = Box::into_raw(Box::new((cgcx, handler)));
299323
unsafe {
300324
let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
@@ -305,6 +329,9 @@ impl<'a> DiagnosticHandlers<'a> {
305329
remark_passes_all,
306330
remark_passes.as_ptr(),
307331
remark_passes.len(),
332+
// The `as_ref()` is important here, otherwise the `CString` will be dropped
333+
// too soon!
334+
remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
308335
);
309336
DiagnosticHandlers { data, llcx, old_handler }
310337
}
@@ -523,7 +550,8 @@ pub(crate) unsafe fn optimize(
523550

524551
let llmod = module.module_llvm.llmod();
525552
let llcx = &*module.module_llvm.llcx;
526-
let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
553+
let _handlers =
554+
DiagnosticHandlers::new(cgcx, diag_handler, llcx, module, CodegenDiagnosticsSection::Opt);
527555

528556
let module_name = module.name.clone();
529557
let module_name = Some(&module_name[..]);
@@ -582,7 +610,13 @@ pub(crate) unsafe fn codegen(
582610
let tm = &*module.module_llvm.tm;
583611
let module_name = module.name.clone();
584612
let module_name = Some(&module_name[..]);
585-
let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
613+
let _handlers = DiagnosticHandlers::new(
614+
cgcx,
615+
diag_handler,
616+
llcx,
617+
&module,
618+
CodegenDiagnosticsSection::Codegen,
619+
);
586620

587621
if cgcx.msvc_imps_needed {
588622
create_msvc_imps(cgcx, llcx, llmod);
@@ -775,7 +809,6 @@ pub(crate) unsafe fn codegen(
775809
}
776810

777811
record_llvm_cgu_instructions_stats(&cgcx.prof, llmod);
778-
drop(handlers);
779812
}
780813

781814
// `.dwo` files are only emitted if:

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

+1
Original file line numberDiff line numberDiff line change
@@ -2512,6 +2512,7 @@ extern "C" {
25122512
remark_all_passes: bool,
25132513
remark_passes: *const *const c_char,
25142514
remark_passes_len: usize,
2515+
remark_file: *const c_char,
25152516
);
25162517

25172518
#[allow(improper_ctypes)]

compiler/rustc_codegen_ssa/src/back/write.rs

+14
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,9 @@ pub struct CodegenContext<B: WriteBackendMethods> {
345345
pub diag_emitter: SharedEmitter,
346346
/// LLVM optimizations for which we want to print remarks.
347347
pub remark: Passes,
348+
/// Directory into which should the LLVM optimization remarks be written.
349+
/// If `None`, they will be written to stderr.
350+
pub remark_dir: Option<PathBuf>,
348351
/// Worker thread number
349352
pub worker: usize,
350353
/// The incremental compilation session directory, or None if we are not
@@ -1041,6 +1044,16 @@ fn start_executing_work<B: ExtraBackendMethods>(
10411044
tcx.backend_optimization_level(())
10421045
};
10431046
let backend_features = tcx.global_backend_features(());
1047+
1048+
let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1049+
// Should this be here?
1050+
// Can this conflict with a parallel attempt to create this directory?
1051+
fs::create_dir_all(dir).expect("Cannot create remark directory");
1052+
Some(dir.canonicalize().expect("Cannot canonicalize remark directory"))
1053+
} else {
1054+
None
1055+
};
1056+
10441057
let cgcx = CodegenContext::<B> {
10451058
crate_types: sess.crate_types().to_vec(),
10461059
each_linked_rlib_for_lto,
@@ -1052,6 +1065,7 @@ fn start_executing_work<B: ExtraBackendMethods>(
10521065
prof: sess.prof.clone(),
10531066
exported_symbols,
10541067
remark: sess.opts.cg.remark.clone(),
1068+
remark_dir,
10551069
worker: 0,
10561070
incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
10571071
cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

+67-7
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,12 @@
77
#include "llvm/IR/Instructions.h"
88
#include "llvm/IR/Intrinsics.h"
99
#include "llvm/IR/IntrinsicsARM.h"
10+
#include "llvm/IR/LLVMRemarkStreamer.h"
1011
#include "llvm/IR/Mangler.h"
12+
#include "llvm/Remarks/RemarkStreamer.h"
13+
#include "llvm/Remarks/RemarkSerializer.h"
14+
#include "llvm/Remarks/RemarkFormat.h"
15+
#include "llvm/Support/ToolOutputFile.h"
1116
#if LLVM_VERSION_GE(16, 0)
1217
#include "llvm/Support/ModRef.h"
1318
#endif
@@ -1855,23 +1860,41 @@ using LLVMDiagnosticHandlerTy = DiagnosticHandler::DiagnosticHandlerTy;
18551860
// When RemarkAllPasses is true, remarks are enabled for all passes. Otherwise
18561861
// the RemarkPasses array specifies individual passes for which remarks will be
18571862
// enabled.
1863+
//
1864+
// If RemarkFilePath is not NULL, optimization remarks will be streamed directly into this file,
1865+
// bypassing the diagnostics handler.
18581866
extern "C" void LLVMRustContextConfigureDiagnosticHandler(
18591867
LLVMContextRef C, LLVMDiagnosticHandlerTy DiagnosticHandlerCallback,
18601868
void *DiagnosticHandlerContext, bool RemarkAllPasses,
1861-
const char * const * RemarkPasses, size_t RemarkPassesLen) {
1869+
const char * const * RemarkPasses, size_t RemarkPassesLen,
1870+
const char * RemarkFilePath
1871+
) {
18621872

18631873
class RustDiagnosticHandler final : public DiagnosticHandler {
18641874
public:
1865-
RustDiagnosticHandler(LLVMDiagnosticHandlerTy DiagnosticHandlerCallback,
1866-
void *DiagnosticHandlerContext,
1867-
bool RemarkAllPasses,
1868-
std::vector<std::string> RemarkPasses)
1875+
RustDiagnosticHandler(
1876+
LLVMDiagnosticHandlerTy DiagnosticHandlerCallback,
1877+
void *DiagnosticHandlerContext,
1878+
bool RemarkAllPasses,
1879+
std::vector<std::string> RemarkPasses,
1880+
std::unique_ptr<llvm::remarks::RemarkStreamer> RemarkStreamer,
1881+
std::unique_ptr<ToolOutputFile> RemarksFile
1882+
)
18691883
: DiagnosticHandlerCallback(DiagnosticHandlerCallback),
18701884
DiagnosticHandlerContext(DiagnosticHandlerContext),
18711885
RemarkAllPasses(RemarkAllPasses),
1872-
RemarkPasses(RemarkPasses) {}
1886+
RemarkPasses(std::move(RemarkPasses)),
1887+
RemarkStreamer(std::move(RemarkStreamer)),
1888+
RemarksFile(std::move(RemarksFile)) {}
18731889

18741890
virtual bool handleDiagnostics(const DiagnosticInfo &DI) override {
1891+
if (this->RemarkStreamer) {
1892+
if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) {
1893+
LLVMRemarkStreamer Streamer(*this->RemarkStreamer);
1894+
Streamer.emit(*OptDiagBase);
1895+
return true;
1896+
}
1897+
}
18751898
if (DiagnosticHandlerCallback) {
18761899
DiagnosticHandlerCallback(DI, DiagnosticHandlerContext);
18771900
return true;
@@ -1912,14 +1935,51 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler(
19121935

19131936
bool RemarkAllPasses = false;
19141937
std::vector<std::string> RemarkPasses;
1938+
std::unique_ptr<llvm::remarks::RemarkStreamer> RemarkStreamer;
1939+
std::unique_ptr<ToolOutputFile> RemarksFile;
19151940
};
19161941

19171942
std::vector<std::string> Passes;
19181943
for (size_t I = 0; I != RemarkPassesLen; ++I)
1944+
{
19191945
Passes.push_back(RemarkPasses[I]);
1946+
}
1947+
1948+
// We need to hold onto both the streamer and the opened file
1949+
std::unique_ptr<llvm::remarks::RemarkStreamer> RemarkStreamer;
1950+
std::unique_ptr<ToolOutputFile> RemarkFile;
1951+
1952+
if (RemarkFilePath != nullptr) {
1953+
std::error_code EC;
1954+
RemarkFile = std::make_unique<ToolOutputFile>(
1955+
RemarkFilePath,
1956+
EC,
1957+
llvm::sys::fs::OF_TextWithCRLF
1958+
);
1959+
// Do not delete the file after we gather remarks
1960+
RemarkFile->keep();
1961+
1962+
auto RemarkSerializer = remarks::createRemarkSerializer(
1963+
llvm::remarks::Format::YAML,
1964+
remarks::SerializerMode::Separate,
1965+
RemarkFile->os()
1966+
);
1967+
if (Error E = RemarkSerializer.takeError())
1968+
{
1969+
// Is this OK?
1970+
report_fatal_error("Cannot create remark serializer");
1971+
}
1972+
RemarkStreamer = std::make_unique<llvm::remarks::RemarkStreamer>(std::move(*RemarkSerializer));
1973+
}
19201974

19211975
unwrap(C)->setDiagnosticHandler(std::make_unique<RustDiagnosticHandler>(
1922-
DiagnosticHandlerCallback, DiagnosticHandlerContext, RemarkAllPasses, Passes));
1976+
DiagnosticHandlerCallback,
1977+
DiagnosticHandlerContext,
1978+
RemarkAllPasses,
1979+
Passes,
1980+
std::move(RemarkStreamer),
1981+
std::move(RemarkFile)
1982+
));
19231983
}
19241984

19251985
extern "C" void LLVMRustGetMangledName(LLVMValueRef V, RustStringRef Str) {

compiler/rustc_session/src/config.rs

+4
Original file line numberDiff line numberDiff line change
@@ -2583,6 +2583,10 @@ pub fn build_session_options(
25832583
handler.early_warn("-C remark requires \"-C debuginfo=n\" to show source locations");
25842584
}
25852585

2586+
if cg.remark.is_empty() && unstable_opts.remark_dir.is_some() {
2587+
handler.early_warn("using -C remark-dir without enabling remarks using e.g. -C remark=all");
2588+
}
2589+
25862590
let externs = parse_externs(handler, matches, &unstable_opts);
25872591

25882592
let crate_name = matches.opt_str("crate-name");

compiler/rustc_session/src/options.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1314,7 +1314,7 @@ options! {
13141314
"control generation of position-independent code (PIC) \
13151315
(`rustc --print relocation-models` for details)"),
13161316
remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1317-
"print remarks for these optimization passes (space separated, or \"all\")"),
1317+
"output remarks for these optimization passes (space separated, or \"all\")"),
13181318
rpath: bool = (false, parse_bool, [UNTRACKED],
13191319
"set rpath values in libs/exes (default: no)"),
13201320
save_temps: bool = (false, parse_bool, [UNTRACKED],
@@ -1659,6 +1659,9 @@ options! {
16591659
"choose which RELRO level to use"),
16601660
remap_cwd_prefix: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
16611661
"remap paths under the current working directory to this path prefix"),
1662+
remark_dir: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1663+
"directory into which to write optimization remarks (if not specified, they will be \
1664+
written to standard error output)"),
16621665
report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
16631666
"immediately print bugs registered with `delay_span_bug` (default: no)"),
16641667
sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED],

0 commit comments

Comments
 (0)