Skip to content

Commit edda37a

Browse files
authored
Rollup merge of rust-lang#101005 - SLASHLogin:rustc_codegen_llvm_diagnostics, r=davidtwco
Migrate rustc_codegen_llvm to SessionDiagnostics WIP: Port current implementation of diagnostics to the new SessionDiagnostics. Part of rust-lang#100717 `@rustbot` label +A-translation
2 parents cc9b259 + caada74 commit edda37a

File tree

19 files changed

+330
-84
lines changed

19 files changed

+330
-84
lines changed

Diff for: compiler/rustc_codegen_llvm/src/attributes.rs

+10-8
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType, StackProtec
1212
use smallvec::SmallVec;
1313

1414
use crate::attributes;
15+
use crate::errors::{MissingFeatures, SanitizerMemtagRequiresMte, TargetFeatureDisableOrEnable};
1516
use crate::llvm::AttributePlace::Function;
1617
use crate::llvm::{self, AllocKindFlags, Attribute, AttributeKind, AttributePlace, MemoryEffects};
1718
use crate::llvm_util;
@@ -82,7 +83,7 @@ pub fn sanitize_attrs<'ll>(
8283
let mte_feature =
8384
features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
8485
if let None | Some("-mte") = mte_feature {
85-
cx.tcx.sess.err("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`");
86+
cx.tcx.sess.emit_err(SanitizerMemtagRequiresMte);
8687
}
8788

8889
attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
@@ -393,13 +394,14 @@ pub fn from_fn_attrs<'ll, 'tcx>(
393394
.get_attrs(instance.def_id(), sym::target_feature)
394395
.next()
395396
.map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
396-
let msg = format!(
397-
"the target features {} must all be either enabled or disabled together",
398-
f.join(", ")
399-
);
400-
let mut err = cx.tcx.sess.struct_span_err(span, &msg);
401-
err.help("add the missing features in a `target_feature` attribute");
402-
err.emit();
397+
cx.tcx
398+
.sess
399+
.create_err(TargetFeatureDisableOrEnable {
400+
features: f,
401+
span: Some(span),
402+
missing_features: Some(MissingFeatures),
403+
})
404+
.emit();
403405
return;
404406
}
405407

Diff for: compiler/rustc_codegen_llvm/src/back/archive.rs

+20-15
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ use std::str;
1212
use object::read::macho::FatArch;
1313

1414
use crate::common;
15+
use crate::errors::{
16+
ArchiveBuildFailure, DlltoolFailImportLibrary, ErrorCallingDllTool, ErrorCreatingImportLibrary,
17+
ErrorWritingDEFFile, UnknownArchiveKind,
18+
};
1519
use crate::llvm::archive_ro::{ArchiveRO, Child};
1620
use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport};
1721
use rustc_codegen_ssa::back::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
@@ -147,7 +151,7 @@ impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> {
147151
fn build(mut self: Box<Self>, output: &Path) -> bool {
148152
match self.build_with_llvm(output) {
149153
Ok(any_members) => any_members,
150-
Err(e) => self.sess.fatal(&format!("failed to build archive: {}", e)),
154+
Err(e) => self.sess.emit_fatal(ArchiveBuildFailure { error: e }),
151155
}
152156
}
153157
}
@@ -217,7 +221,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
217221
match std::fs::write(&def_file_path, def_file_content) {
218222
Ok(_) => {}
219223
Err(e) => {
220-
sess.fatal(&format!("Error writing .DEF file: {}", e));
224+
sess.emit_fatal(ErrorWritingDEFFile { error: e });
221225
}
222226
};
223227

@@ -239,13 +243,14 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
239243

240244
match result {
241245
Err(e) => {
242-
sess.fatal(&format!("Error calling dlltool: {}", e));
246+
sess.emit_fatal(ErrorCallingDllTool { error: e });
247+
}
248+
Ok(output) if !output.status.success() => {
249+
sess.emit_fatal(DlltoolFailImportLibrary {
250+
stdout: String::from_utf8_lossy(&output.stdout),
251+
stderr: String::from_utf8_lossy(&output.stderr),
252+
})
243253
}
244-
Ok(output) if !output.status.success() => sess.fatal(&format!(
245-
"Dlltool could not create import library: {}\n{}",
246-
String::from_utf8_lossy(&output.stdout),
247-
String::from_utf8_lossy(&output.stderr)
248-
)),
249254
_ => {}
250255
}
251256
} else {
@@ -293,11 +298,10 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
293298
};
294299

295300
if result == crate::llvm::LLVMRustResult::Failure {
296-
sess.fatal(&format!(
297-
"Error creating import library for {}: {}",
301+
sess.emit_fatal(ErrorCreatingImportLibrary {
298302
lib_name,
299-
llvm::last_error().unwrap_or("unknown LLVM error".to_string())
300-
));
303+
error: llvm::last_error().unwrap_or("unknown LLVM error".to_string()),
304+
});
301305
}
302306
};
303307

@@ -308,9 +312,10 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
308312
impl<'a> LlvmArchiveBuilder<'a> {
309313
fn build_with_llvm(&mut self, output: &Path) -> io::Result<bool> {
310314
let kind = &*self.sess.target.archive_format;
311-
let kind = kind.parse::<ArchiveKind>().map_err(|_| kind).unwrap_or_else(|kind| {
312-
self.sess.fatal(&format!("Don't know how to build archive of type: {}", kind))
313-
});
315+
let kind = kind
316+
.parse::<ArchiveKind>()
317+
.map_err(|_| kind)
318+
.unwrap_or_else(|kind| self.sess.emit_fatal(UnknownArchiveKind { kind }));
314319

315320
let mut additions = mem::take(&mut self.additions);
316321
let mut strings = Vec::new();

Diff for: compiler/rustc_codegen_llvm/src/back/lto.rs

+2-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::back::write::{self, save_temp_bitcode, DiagnosticHandlers};
2+
use crate::errors::DynamicLinkingWithLTO;
23
use crate::llvm::{self, build_string};
34
use crate::{LlvmCodegenBackend, ModuleLlvm};
45
use object::read::archive::ArchiveFile;
@@ -90,13 +91,7 @@ fn prepare_lto(
9091
}
9192

9293
if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
93-
diag_handler
94-
.struct_err("cannot prefer dynamic linking when performing LTO")
95-
.note(
96-
"only 'staticlib', 'bin', and 'cdylib' outputs are \
97-
supported with LTO",
98-
)
99-
.emit();
94+
diag_handler.emit_err(DynamicLinkingWithLTO);
10095
return Err(FatalError);
10196
}
10297

Diff for: compiler/rustc_codegen_llvm/src/consts.rs

+7-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::base;
22
use crate::common::{self, CodegenCx};
33
use crate::debuginfo;
4+
use crate::errors::{InvalidMinimumAlignment, LinkageConstOrMutType, SymbolAlreadyDefined};
45
use crate::llvm::{self, True};
56
use crate::llvm_util;
67
use crate::type_::Type;
@@ -146,7 +147,7 @@ fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align:
146147
match Align::from_bits(min) {
147148
Ok(min) => align = align.max(min),
148149
Err(err) => {
149-
cx.sess().err(&format!("invalid minimum global alignment: {}", err));
150+
cx.sess().emit_err(InvalidMinimumAlignment { err });
150151
}
151152
}
152153
}
@@ -174,10 +175,7 @@ fn check_and_apply_linkage<'ll, 'tcx>(
174175
let llty2 = if let ty::RawPtr(ref mt) = ty.kind() {
175176
cx.layout_of(mt.ty).llvm_type(cx)
176177
} else {
177-
cx.sess().span_fatal(
178-
cx.tcx.def_span(def_id),
179-
"must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
180-
)
178+
cx.sess().emit_fatal(LinkageConstOrMutType { span: cx.tcx.def_span(def_id) })
181179
};
182180
unsafe {
183181
// Declare a symbol `foo` with the desired linkage.
@@ -193,10 +191,10 @@ fn check_and_apply_linkage<'ll, 'tcx>(
193191
let mut real_name = "_rust_extern_with_linkage_".to_string();
194192
real_name.push_str(sym);
195193
let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
196-
cx.sess().span_fatal(
197-
cx.tcx.def_span(def_id),
198-
&format!("symbol `{}` is already defined", &sym),
199-
)
194+
cx.sess().emit_fatal(SymbolAlreadyDefined {
195+
span: cx.tcx.def_span(def_id),
196+
symbol_name: sym,
197+
})
200198
});
201199
llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
202200
llvm::LLVMSetInitializer(g2, g1);

Diff for: compiler/rustc_codegen_llvm/src/context.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use crate::back::write::to_llvm_code_model;
33
use crate::callee::get_fn;
44
use crate::coverageinfo;
55
use crate::debuginfo;
6+
use crate::errors::BranchProtectionRequiresAArch64;
67
use crate::llvm;
78
use crate::llvm_util;
89
use crate::type_::Type;
@@ -26,6 +27,7 @@ use rustc_session::config::{BranchProtection, CFGuard, CFProtection};
2627
use rustc_session::config::{CrateType, DebugInfo, PAuthKey, PacRet};
2728
use rustc_session::Session;
2829
use rustc_span::source_map::Span;
30+
use rustc_span::source_map::Spanned;
2931
use rustc_target::abi::{
3032
call::FnAbi, HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx,
3133
};
@@ -275,7 +277,7 @@ pub unsafe fn create_module<'ll>(
275277

276278
if let Some(BranchProtection { bti, pac_ret }) = sess.opts.unstable_opts.branch_protection {
277279
if sess.target.arch != "aarch64" {
278-
sess.err("-Zbranch-protection is only supported on aarch64");
280+
sess.emit_err(BranchProtectionRequiresAArch64);
279281
} else {
280282
llvm::LLVMRustAddModuleFlag(
281283
llmod,
@@ -951,7 +953,7 @@ impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
951953
#[inline]
952954
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
953955
if let LayoutError::SizeOverflow(_) = err {
954-
self.sess().span_fatal(span, &err.to_string())
956+
self.sess().emit_fatal(Spanned { span, node: err })
955957
} else {
956958
span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
957959
}
@@ -969,7 +971,7 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
969971
fn_abi_request: FnAbiRequest<'tcx>,
970972
) -> ! {
971973
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
972-
self.sess().span_fatal(span, &err.to_string())
974+
self.sess().emit_fatal(Spanned { span, node: err })
973975
} else {
974976
match fn_abi_request {
975977
FnAbiRequest::OfFnPtr { sig, extra_args } => {

Diff for: compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use crate::common::CodegenCx;
22
use crate::coverageinfo;
3+
use crate::errors::InstrumentCoverageRequiresLLVM12;
34
use crate::llvm;
45

56
use llvm::coverageinfo::CounterMappingRegion;
@@ -37,7 +38,7 @@ pub fn finalize<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) {
3738
// LLVM 12.
3839
let version = coverageinfo::mapping_version();
3940
if version < 4 {
40-
tcx.sess.fatal("rustc option `-C instrument-coverage` requires LLVM 12 or higher.");
41+
tcx.sess.emit_fatal(InstrumentCoverageRequiresLLVM12);
4142
}
4243

4344
debug!("Generating coverage map for CodegenUnit: `{}`", cx.codegen_unit.name());

Diff for: compiler/rustc_codegen_llvm/src/errors.rs

+139
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
use std::borrow::Cow;
2+
3+
use rustc_errors::fluent;
4+
use rustc_errors::DiagnosticBuilder;
5+
use rustc_errors::ErrorGuaranteed;
6+
use rustc_errors::Handler;
7+
use rustc_errors::IntoDiagnostic;
8+
use rustc_macros::{Diagnostic, Subdiagnostic};
9+
use rustc_span::Span;
10+
11+
#[derive(Diagnostic)]
12+
#[diag(codegen_llvm_unknown_ctarget_feature_prefix)]
13+
#[note]
14+
pub(crate) struct UnknownCTargetFeaturePrefix<'a> {
15+
pub feature: &'a str,
16+
}
17+
18+
#[derive(Diagnostic)]
19+
#[diag(codegen_llvm_unknown_ctarget_feature)]
20+
#[note]
21+
pub(crate) struct UnknownCTargetFeature<'a> {
22+
pub feature: &'a str,
23+
#[subdiagnostic]
24+
pub rust_feature: PossibleFeature<'a>,
25+
}
26+
27+
#[derive(Subdiagnostic)]
28+
pub(crate) enum PossibleFeature<'a> {
29+
#[help(possible_feature)]
30+
Some { rust_feature: &'a str },
31+
#[help(consider_filing_feature_request)]
32+
None,
33+
}
34+
35+
#[derive(Diagnostic)]
36+
#[diag(codegen_llvm_error_creating_import_library)]
37+
pub(crate) struct ErrorCreatingImportLibrary<'a> {
38+
pub lib_name: &'a str,
39+
pub error: String,
40+
}
41+
42+
#[derive(Diagnostic)]
43+
#[diag(codegen_llvm_instrument_coverage_requires_llvm_12)]
44+
pub(crate) struct InstrumentCoverageRequiresLLVM12;
45+
46+
#[derive(Diagnostic)]
47+
#[diag(codegen_llvm_symbol_already_defined)]
48+
pub(crate) struct SymbolAlreadyDefined<'a> {
49+
#[primary_span]
50+
pub span: Span,
51+
pub symbol_name: &'a str,
52+
}
53+
54+
#[derive(Diagnostic)]
55+
#[diag(codegen_llvm_branch_protection_requires_aarch64)]
56+
pub(crate) struct BranchProtectionRequiresAArch64;
57+
58+
#[derive(Diagnostic)]
59+
#[diag(codegen_llvm_invalid_minimum_alignment)]
60+
pub(crate) struct InvalidMinimumAlignment {
61+
pub err: String,
62+
}
63+
64+
#[derive(Diagnostic)]
65+
#[diag(codegen_llvm_linkage_const_or_mut_type)]
66+
pub(crate) struct LinkageConstOrMutType {
67+
#[primary_span]
68+
pub span: Span,
69+
}
70+
71+
#[derive(Diagnostic)]
72+
#[diag(codegen_llvm_sanitizer_memtag_requires_mte)]
73+
pub(crate) struct SanitizerMemtagRequiresMte;
74+
75+
#[derive(Diagnostic)]
76+
#[diag(codegen_llvm_archive_build_failure)]
77+
pub(crate) struct ArchiveBuildFailure {
78+
pub error: std::io::Error,
79+
}
80+
81+
#[derive(Diagnostic)]
82+
#[diag(codegen_llvm_error_writing_def_file)]
83+
pub(crate) struct ErrorWritingDEFFile {
84+
pub error: std::io::Error,
85+
}
86+
87+
#[derive(Diagnostic)]
88+
#[diag(codegen_llvm_error_calling_dlltool)]
89+
pub(crate) struct ErrorCallingDllTool {
90+
pub error: std::io::Error,
91+
}
92+
93+
#[derive(Diagnostic)]
94+
#[diag(codegen_llvm_dlltool_fail_import_library)]
95+
pub(crate) struct DlltoolFailImportLibrary<'a> {
96+
pub stdout: Cow<'a, str>,
97+
pub stderr: Cow<'a, str>,
98+
}
99+
100+
#[derive(Diagnostic)]
101+
#[diag(codegen_llvm_unknown_archive_kind)]
102+
pub(crate) struct UnknownArchiveKind<'a> {
103+
pub kind: &'a str,
104+
}
105+
106+
#[derive(Diagnostic)]
107+
#[diag(codegen_llvm_dynamic_linking_with_lto)]
108+
#[note]
109+
pub(crate) struct DynamicLinkingWithLTO;
110+
111+
#[derive(Diagnostic)]
112+
#[diag(codegen_llvm_fail_parsing_target_machine_config_to_target_machine)]
113+
pub(crate) struct FailParsingTargetMachineConfigToTargetMachine {
114+
pub error: String,
115+
}
116+
117+
pub(crate) struct TargetFeatureDisableOrEnable<'a> {
118+
pub features: &'a [&'a str],
119+
pub span: Option<Span>,
120+
pub missing_features: Option<MissingFeatures>,
121+
}
122+
123+
#[derive(Subdiagnostic)]
124+
#[help(codegen_llvm_missing_features)]
125+
pub(crate) struct MissingFeatures;
126+
127+
impl IntoDiagnostic<'_, ErrorGuaranteed> for TargetFeatureDisableOrEnable<'_> {
128+
fn into_diagnostic(self, sess: &'_ Handler) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
129+
let mut diag = sess.struct_err(fluent::codegen_llvm_target_feature_disable_or_enable);
130+
if let Some(span) = self.span {
131+
diag.set_span(span);
132+
};
133+
if let Some(missing_features) = self.missing_features {
134+
diag.subdiagnostic(missing_features);
135+
}
136+
diag.set_arg("features", self.features.join(", "));
137+
diag
138+
}
139+
}

0 commit comments

Comments
 (0)