Auto merge of #119146 - nnethercote:rm-DiagCtxt-api-duplication, r=compiler-errors

Remove `DiagCtxt` API duplication

`DiagCtxt` defines the internal API for creating and emitting diagnostics: methods like `struct_err`, `struct_span_warn`, `note`, `create_fatal`, `emit_bug`. There are over 50 methods.

Some of these methods are then duplicated across several other types: `Session`, `ParseSess`, `Parser`, `ExtCtxt`, and `MirBorrowckCtxt`. `Session` duplicates the most, though half the ones it does are unused. Each duplicated method just calls forward to the corresponding method in `DiagCtxt`. So this duplication exists to (in the best case) shorten chains like `ecx.tcx.sess.parse_sess.dcx.emit_err()` to `ecx.emit_err()`.

This API duplication is ugly and has been bugging me for a while. And it's inconsistent: there's no real logic about which methods are duplicated, and the use of `#[rustc_lint_diagnostic]` and `#[track_caller]` attributes vary across the duplicates.

This PR removes the duplicated API methods and makes all diagnostic creation and emission go through `DiagCtxt`. It also adds `dcx` getter methods to several types to shorten chains. This approach scales *much* better than API duplication; indeed, the PR adds `dcx()` to numerous types that didn't have API duplication: `TyCtxt`, `LoweringCtxt`, `ConstCx`, `FnCtxt`, `TypeErrCtxt`, `InferCtxt`, `CrateLoader`, `CheckAttrVisitor`, and `Resolver`. These result in a lot of changes from `foo.tcx.sess.emit_err()` to `foo.dcx().emit_err()`. (You could do this with more types, but it gets into diminishing returns territory for types that don't emit many diagnostics.)

After all these changes, some call sites are more verbose, some are less verbose, and many are the same. The total number of lines is reduced, mostly because of the removed API duplication. And consistency is increased, because calls to `emit_err` and friends are always preceded with `.dcx()` or `.dcx`.

r? `@compiler-errors`
This commit is contained in:
bors 2023-12-26 02:24:39 +00:00
commit bcae781754
16 changed files with 79 additions and 69 deletions

View File

@ -47,12 +47,12 @@ pub(crate) fn conv_to_call_conv(sess: &Session, c: Conv, default_call_conv: Call
} }
Conv::X86Intr | Conv::RiscvInterrupt { .. } => { Conv::X86Intr | Conv::RiscvInterrupt { .. } => {
sess.fatal(format!("interrupt call conv {c:?} not yet implemented")) sess.dcx().fatal(format!("interrupt call conv {c:?} not yet implemented"))
} }
Conv::ArmAapcs => sess.fatal("aapcs call conv not yet implemented"), Conv::ArmAapcs => sess.dcx().fatal("aapcs call conv not yet implemented"),
Conv::CCmseNonSecureCall => { Conv::CCmseNonSecureCall => {
sess.fatal("C-cmse-nonsecure-call call conv is not yet implemented"); sess.dcx().fatal("C-cmse-nonsecure-call call conv is not yet implemented");
} }
Conv::Msp430Intr Conv::Msp430Intr
@ -88,10 +88,10 @@ pub(crate) fn import_function<'tcx>(
let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst); let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst);
match module.declare_function(name, Linkage::Import, &sig) { match module.declare_function(name, Linkage::Import, &sig) {
Ok(func_id) => func_id, Ok(func_id) => func_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
"attempt to declare `{name}` as function, but it was already declared as static" "attempt to declare `{name}` as function, but it was already declared as static"
)), )),
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.dcx().fatal(format!(
"attempt to declare `{name}` with signature {new_sig:?}, \ "attempt to declare `{name}` with signature {new_sig:?}, \
but it was already declared with signature {prev_sig:?}" but it was already declared with signature {prev_sig:?}"
)), )),
@ -181,7 +181,7 @@ fn make_local_place<'tcx>(
is_ssa: bool, is_ssa: bool,
) -> CPlace<'tcx> { ) -> CPlace<'tcx> {
if layout.is_unsized() { if layout.is_unsized() {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.local_decls[local].source_info.span, fx.mir.local_decls[local].source_info.span,
"unsized locals are not yet supported", "unsized locals are not yet supported",
); );
@ -226,7 +226,7 @@ enum ArgKind<'tcx> {
// FIXME implement variadics in cranelift // FIXME implement variadics in cranelift
if fn_abi.c_variadic { if fn_abi.c_variadic {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.span, fx.mir.span,
"Defining variadic functions is not yet supported by Cranelift", "Defining variadic functions is not yet supported by Cranelift",
); );
@ -543,7 +543,7 @@ enum CallTarget {
// FIXME find a cleaner way to support varargs // FIXME find a cleaner way to support varargs
if fn_sig.c_variadic() { if fn_sig.c_variadic() {
if !matches!(fn_sig.abi(), Abi::C { .. }) { if !matches!(fn_sig.abi(), Abi::C { .. }) {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
format!("Variadic call for non-C abi {:?}", fn_sig.abi()), format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
); );
@ -555,7 +555,7 @@ enum CallTarget {
let ty = fx.bcx.func.dfg.value_type(arg); let ty = fx.bcx.func.dfg.value_type(arg);
if !ty.is_int() { if !ty.is_int() {
// FIXME set %al to upperbound on float args once floats are supported // FIXME set %al to upperbound on float args once floats are supported
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
format!("Non int ty {:?} for variadic call", ty), format!("Non int ty {:?} for variadic call", ty),
); );

View File

@ -236,13 +236,13 @@ pub(crate) fn verify_func(
match cranelift_codegen::verify_function(&func, &flags) { match cranelift_codegen::verify_function(&func, &flags) {
Ok(_) => {} Ok(_) => {}
Err(err) => { Err(err) => {
tcx.sess.err(format!("{:?}", err)); tcx.dcx().err(format!("{:?}", err));
let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error( let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
&func, &func,
Some(Box::new(writer)), Some(Box::new(writer)),
err, err,
); );
tcx.sess.fatal(format!("cranelift verify error:\n{}", pretty_error)); tcx.dcx().fatal(format!("cranelift verify error:\n{}", pretty_error));
} }
} }
}); });
@ -450,7 +450,7 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
unwind: _, unwind: _,
} => { } => {
if options.contains(InlineAsmOptions::MAY_UNWIND) { if options.contains(InlineAsmOptions::MAY_UNWIND) {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
"cranelift doesn't support unwinding from inline assembly.", "cranelift doesn't support unwinding from inline assembly.",
); );
@ -812,7 +812,7 @@ fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
| StatementKind::PlaceMention(..) | StatementKind::PlaceMention(..)
| StatementKind::AscribeUserType(..) => {} | StatementKind::AscribeUserType(..) => {}
StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"), StatementKind::Coverage { .. } => fx.tcx.dcx().fatal("-Zcoverage is unimplemented"),
StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic { StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
// We ignore `assume` intrinsics, they are only useful for optimizations // We ignore `assume` intrinsics, they are only useful for optimizations
NonDivergingIntrinsic::Assume(_) => {} NonDivergingIntrinsic::Assume(_) => {}

View File

@ -465,9 +465,12 @@ impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
#[inline] #[inline]
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err { if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
self.0.sess.span_fatal(span, err.to_string()) self.0.sess.dcx().span_fatal(span, err.to_string())
} else { } else {
self.0.sess.span_fatal(span, format!("failed to get layout for `{}`: {}", ty, err)) self.0
.sess
.dcx()
.span_fatal(span, format!("failed to get layout for `{}`: {}", ty, err))
} }
} }
} }
@ -483,7 +486,7 @@ fn handle_fn_abi_err(
fn_abi_request: FnAbiRequest<'tcx>, fn_abi_request: FnAbiRequest<'tcx>,
) -> ! { ) -> ! {
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err { if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
self.0.sess.emit_fatal(Spanned { span, node: err }) self.0.sess.dcx().emit_fatal(Spanned { span, node: err })
} else { } else {
match fn_abi_request { match fn_abi_request {
FnAbiRequest::OfFnPtr { sig, extra_args } => { FnAbiRequest::OfFnPtr { sig, extra_args } => {

View File

@ -263,7 +263,7 @@ fn data_id_for_static(
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
) { ) {
Ok(data_id) => data_id, Ok(data_id) => data_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
"attempt to declare `{symbol_name}` as static, but it was already declared as function" "attempt to declare `{symbol_name}` as static, but it was already declared as function"
)), )),
Err(err) => Err::<_, _>(err).unwrap(), Err(err) => Err::<_, _>(err).unwrap(),
@ -311,7 +311,7 @@ fn data_id_for_static(
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
) { ) {
Ok(data_id) => data_id, Ok(data_id) => data_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
"attempt to declare `{symbol_name}` as static, but it was already declared as function" "attempt to declare `{symbol_name}` as static, but it was already declared as function"
)), )),
Err(err) => Err::<_, _>(err).unwrap(), Err(err) => Err::<_, _>(err).unwrap(),
@ -360,7 +360,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
if let Some(names) = section_name.split_once(',') { if let Some(names) = section_name.split_once(',') {
names names
} else { } else {
tcx.sess.fatal(format!( tcx.dcx().fatal(format!(
"#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma", "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
section_name section_name
)); ));
@ -406,7 +406,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
GlobalAlloc::Static(def_id) => { GlobalAlloc::Static(def_id) => {
if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
{ {
tcx.sess.fatal(format!( tcx.dcx().fatal(format!(
"Allocation {:?} contains reference to TLS value {:?}", "Allocation {:?} contains reference to TLS value {:?}",
alloc_id, def_id alloc_id, def_id
)); ));

View File

@ -69,7 +69,7 @@ pub(crate) fn join(
let module_codegen_result = match module_codegen_result { let module_codegen_result = match module_codegen_result {
Ok(module_codegen_result) => module_codegen_result, Ok(module_codegen_result) => module_codegen_result,
Err(err) => sess.fatal(err), Err(err) => sess.dcx().fatal(err),
}; };
let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } = let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } =
module_codegen_result; module_codegen_result;
@ -108,7 +108,7 @@ pub(crate) fn join(
self.concurrency_limiter.finished(); self.concurrency_limiter.finished();
sess.abort_if_errors(); sess.dcx().abort_if_errors();
( (
CodegenResults { CodegenResults {
@ -422,7 +422,7 @@ pub(crate) fn run_aot(
backend_config.clone(), backend_config.clone(),
global_asm_config.clone(), global_asm_config.clone(),
cgu.name(), cgu.name(),
concurrency_limiter.acquire(tcx.sess.dcx()), concurrency_limiter.acquire(tcx.dcx()),
), ),
module_codegen, module_codegen,
Some(rustc_middle::dep_graph::hash_result), Some(rustc_middle::dep_graph::hash_result),
@ -455,7 +455,7 @@ pub(crate) fn run_aot(
"allocator_shim".to_owned(), "allocator_shim".to_owned(),
) { ) {
Ok(allocator_module) => Some(allocator_module), Ok(allocator_module) => Some(allocator_module),
Err(err) => tcx.sess.fatal(err), Err(err) => tcx.dcx().fatal(err),
} }
} else { } else {
None None
@ -478,7 +478,7 @@ pub(crate) fn run_aot(
let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name); let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name);
if let Err(err) = std::fs::write(&tmp_file, obj) { if let Err(err) = std::fs::write(&tmp_file, obj) {
tcx.sess.fatal(format!("error writing metadata object file: {}", err)); tcx.dcx().fatal(format!("error writing metadata object file: {}", err));
} }
(metadata_cgu_name, tmp_file) (metadata_cgu_name, tmp_file)

View File

@ -94,11 +94,11 @@ fn create_jit_module(
pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! { pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
if !tcx.sess.opts.output_types.should_codegen() { if !tcx.sess.opts.output_types.should_codegen() {
tcx.sess.fatal("JIT mode doesn't work with `cargo check`"); tcx.dcx().fatal("JIT mode doesn't work with `cargo check`");
} }
if !tcx.crate_types().contains(&rustc_session::config::CrateType::Executable) { if !tcx.crate_types().contains(&rustc_session::config::CrateType::Executable) {
tcx.sess.fatal("can't jit non-executable crate"); tcx.dcx().fatal("can't jit non-executable crate");
} }
let (mut jit_module, mut cx) = create_jit_module( let (mut jit_module, mut cx) = create_jit_module(
@ -141,17 +141,17 @@ pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
} }
MonoItem::GlobalAsm(item_id) => { MonoItem::GlobalAsm(item_id) => {
let item = tcx.hir().item(item_id); let item = tcx.hir().item(item_id);
tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode"); tcx.dcx().span_fatal(item.span, "Global asm is not supported in JIT mode");
} }
} }
} }
}); });
if !cx.global_asm.is_empty() { if !cx.global_asm.is_empty() {
tcx.sess.fatal("Inline asm is not supported in JIT mode"); tcx.dcx().fatal("Inline asm is not supported in JIT mode");
} }
tcx.sess.abort_if_errors(); tcx.dcx().abort_if_errors();
jit_module.finalize_definitions().unwrap(); jit_module.finalize_definitions().unwrap();
unsafe { cx.unwind_context.register_jit(&jit_module) }; unsafe { cx.unwind_context.register_jit(&jit_module) };
@ -338,7 +338,7 @@ fn dep_symbol_lookup_fn(
.collect::<Box<[_]>>(), .collect::<Box<[_]>>(),
); );
sess.abort_if_errors(); sess.dcx().abort_if_errors();
Box::new(move |sym_name| { Box::new(move |sym_name| {
for dylib in &*imported_dylibs { for dylib in &*imported_dylibs {

View File

@ -47,7 +47,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
} }
InlineAsmOperand::SymFn { anon_const } => { InlineAsmOperand::SymFn { anon_const } => {
if cfg!(not(feature = "inline_asm_sym")) { if cfg!(not(feature = "inline_asm_sym")) {
tcx.sess.span_err( tcx.dcx().span_err(
item.span, item.span,
"asm! and global_asm! sym operands are not yet supported", "asm! and global_asm! sym operands are not yet supported",
); );
@ -65,7 +65,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
} }
InlineAsmOperand::SymStatic { path: _, def_id } => { InlineAsmOperand::SymStatic { path: _, def_id } => {
if cfg!(not(feature = "inline_asm_sym")) { if cfg!(not(feature = "inline_asm_sym")) {
tcx.sess.span_err( tcx.dcx().span_err(
item.span, item.span,
"asm! and global_asm! sym operands are not yet supported", "asm! and global_asm! sym operands are not yet supported",
); );

View File

@ -84,7 +84,7 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>(
InlineAsmOperand::SymFn { ref value } => { InlineAsmOperand::SymFn { ref value } => {
if cfg!(not(feature = "inline_asm_sym")) { if cfg!(not(feature = "inline_asm_sym")) {
fx.tcx fx.tcx
.sess .dcx()
.span_err(span, "asm! and global_asm! sym operands are not yet supported"); .span_err(span, "asm! and global_asm! sym operands are not yet supported");
} }
@ -455,7 +455,7 @@ fn generate_asm_wrapper(&self, asm_name: &str) -> String {
} }
_ => self _ => self
.tcx .tcx
.sess .dcx()
.fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")), .fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")),
} }
@ -563,7 +563,7 @@ fn generate_asm_wrapper(&self, asm_name: &str) -> String {
BinaryFormat::Macho | BinaryFormat::Coff => {} BinaryFormat::Macho | BinaryFormat::Coff => {}
_ => self _ => self
.tcx .tcx
.sess .dcx()
.fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")), .fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")),
} }

View File

@ -68,7 +68,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>(
_ => { _ => {
fx.tcx fx.tcx
.sess .dcx()
.warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic)); .warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
crate::trap::trap_unimplemented(fx, intrinsic); crate::trap::trap_unimplemented(fx, intrinsic);
return; return;

View File

@ -309,7 +309,7 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>(
} }
*/ */
_ => { _ => {
fx.tcx.sess.warn(format!( fx.tcx.dcx().warn(format!(
"unsupported AArch64 llvm intrinsic {}; replacing with trap", "unsupported AArch64 llvm intrinsic {}; replacing with trap",
intrinsic intrinsic
)); ));

View File

@ -960,7 +960,9 @@ fn select4(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal(span, "Index argument for `_mm_cmpestri` is not a constant"); fx.tcx
.dcx()
.span_fatal(span, "Index argument for `_mm_cmpestri` is not a constant");
}; };
let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8)); let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8));
@ -1011,7 +1013,9 @@ fn select4(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal(span, "Index argument for `_mm_cmpestrm` is not a constant"); fx.tcx
.dcx()
.span_fatal(span, "Index argument for `_mm_cmpestrm` is not a constant");
}; };
let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8)); let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8));
@ -1056,7 +1060,7 @@ fn select4(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
"Index argument for `_mm_clmulepi64_si128` is not a constant", "Index argument for `_mm_clmulepi64_si128` is not a constant",
); );
@ -1093,7 +1097,7 @@ fn select4(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
"Index argument for `_mm_aeskeygenassist_si128` is not a constant", "Index argument for `_mm_aeskeygenassist_si128` is not a constant",
); );
@ -1361,7 +1365,7 @@ fn select4(
_ => { _ => {
fx.tcx fx.tcx
.sess .dcx()
.warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic)); .warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic));
crate::trap::trap_unimplemented(fx, intrinsic); crate::trap::trap_unimplemented(fx, intrinsic);
return; return;

View File

@ -37,7 +37,7 @@ fn report_atomic_type_validation_error<'tcx>(
span: Span, span: Span,
ty: Ty<'tcx>, ty: Ty<'tcx>,
) { ) {
fx.tcx.sess.span_err( fx.tcx.dcx().span_err(
span, span,
format!( format!(
"`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`", "`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`",
@ -785,7 +785,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
return; return;
} else { } else {
fx.tcx fx.tcx
.sess .dcx()
.span_fatal(source_info.span, "128bit atomics not yet supported"); .span_fatal(source_info.span, "128bit atomics not yet supported");
} }
} }
@ -816,7 +816,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
return; return;
} else { } else {
fx.tcx fx.tcx
.sess .dcx()
.span_fatal(source_info.span, "128bit atomics not yet supported"); .span_fatal(source_info.span, "128bit atomics not yet supported");
} }
} }
@ -1245,7 +1245,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
// FIXME implement variadics in cranelift // FIXME implement variadics in cranelift
sym::va_copy | sym::va_arg | sym::va_end => { sym::va_copy | sym::va_arg | sym::va_end => {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
"Defining variadic functions is not yet supported by Cranelift", "Defining variadic functions is not yet supported by Cranelift",
); );
@ -1253,7 +1253,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
_ => { _ => {
fx.tcx fx.tcx
.sess .dcx()
.span_fatal(source_info.span, format!("unsupported intrinsic {}", intrinsic)); .span_fatal(source_info.span, format!("unsupported intrinsic {}", intrinsic));
} }
} }

View File

@ -12,7 +12,7 @@ fn report_simd_type_validation_error(
span: Span, span: Span,
ty: Ty<'_>, ty: Ty<'_>,
) { ) {
fx.tcx.sess.span_err(span, format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty)); fx.tcx.dcx().span_err(span, format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty));
// Prevent verifier error // Prevent verifier error
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
} }
@ -192,7 +192,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
.try_into() .try_into()
.unwrap(), .unwrap(),
_ => { _ => {
fx.tcx.sess.span_err( fx.tcx.dcx().span_err(
span, span,
format!("simd_shuffle index must be an array of `u32`, got `{}`", idx_ty), format!("simd_shuffle index must be an array of `u32`, got `{}`", idx_ty),
); );
@ -278,7 +278,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
{ {
idx_const idx_const
} else { } else {
fx.tcx.sess.span_fatal(span, "Index argument for `simd_insert` is not a constant"); fx.tcx.dcx().span_fatal(span, "Index argument for `simd_insert` is not a constant");
}; };
let idx: u32 = idx_const let idx: u32 = idx_const
@ -286,7 +286,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
.unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const)); .unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const));
let (lane_count, _lane_ty) = base.layout().ty.simd_size_and_type(fx.tcx); let (lane_count, _lane_ty) = base.layout().ty.simd_size_and_type(fx.tcx);
if u64::from(idx) >= lane_count { if u64::from(idx) >= lane_count {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.span, fx.mir.span,
format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count), format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count),
); );
@ -316,7 +316,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
{ {
idx_const idx_const
} else { } else {
fx.tcx.sess.span_warn(span, "Index argument for `simd_extract` is not a constant"); fx.tcx.dcx().span_warn(span, "Index argument for `simd_extract` is not a constant");
let trap_block = fx.bcx.create_block(); let trap_block = fx.bcx.create_block();
let true_ = fx.bcx.ins().iconst(types::I8, 1); let true_ = fx.bcx.ins().iconst(types::I8, 1);
let ret_block = fx.get_block(target); let ret_block = fx.get_block(target);
@ -334,7 +334,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
.unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const)); .unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const));
let (lane_count, _lane_ty) = v.layout().ty.simd_size_and_type(fx.tcx); let (lane_count, _lane_ty) = v.layout().ty.simd_size_and_type(fx.tcx);
if u64::from(idx) >= lane_count { if u64::from(idx) >= lane_count {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.span, fx.mir.span,
format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count), format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count),
); );
@ -859,7 +859,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
match lane_ty.kind() { match lane_ty.kind() {
ty::Int(_) | ty::Uint(_) => {} ty::Int(_) | ty::Uint(_) => {}
_ => { _ => {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
format!( format!(
"invalid monomorphization of `simd_bitmask` intrinsic: \ "invalid monomorphization of `simd_bitmask` intrinsic: \
@ -899,7 +899,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
&& len.try_eval_target_usize(fx.tcx, ty::ParamEnv::reveal_all()) && len.try_eval_target_usize(fx.tcx, ty::ParamEnv::reveal_all())
== Some(expected_bytes) => {} == Some(expected_bytes) => {}
_ => { _ => {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
format!( format!(
"invalid monomorphization of `simd_bitmask` intrinsic: \ "invalid monomorphization of `simd_bitmask` intrinsic: \
@ -1117,7 +1117,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
} }
_ => { _ => {
fx.tcx.sess.span_err(span, format!("Unknown SIMD intrinsic {}", intrinsic)); fx.tcx.dcx().span_err(span, format!("Unknown SIMD intrinsic {}", intrinsic));
// Prevent verifier error // Prevent verifier error
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
return; return;

View File

@ -177,13 +177,15 @@ fn init(&self, sess: &Session) {
use rustc_session::config::Lto; use rustc_session::config::Lto;
match sess.lto() { match sess.lto() {
Lto::No | Lto::ThinLocal => {} Lto::No | Lto::ThinLocal => {}
Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."), Lto::Thin | Lto::Fat => {
sess.dcx().warn("LTO is not supported. You may get a linker error.")
}
} }
let mut config = self.config.borrow_mut(); let mut config = self.config.borrow_mut();
if config.is_none() { if config.is_none() {
let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args) let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
.unwrap_or_else(|err| sess.fatal(err)); .unwrap_or_else(|err| sess.dcx().fatal(err));
*config = Some(new_config); *config = Some(new_config);
} }
} }
@ -202,7 +204,7 @@ fn codegen_crate(
metadata: EncodedMetadata, metadata: EncodedMetadata,
need_metadata_module: bool, need_metadata_module: bool,
) -> Box<dyn Any> { ) -> Box<dyn Any> {
tcx.sess.abort_if_errors(); tcx.dcx().abort_if_errors();
let config = self.config.borrow().clone().unwrap(); let config = self.config.borrow().clone().unwrap();
match config.codegen_mode { match config.codegen_mode {
CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module), CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
@ -211,7 +213,7 @@ fn codegen_crate(
driver::jit::run_jit(tcx, config); driver::jit::run_jit(tcx, config);
#[cfg(not(feature = "jit"))] #[cfg(not(feature = "jit"))]
tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift"); tcx.dcx().fatal("jit support was disabled when compiling rustc_codegen_cranelift");
} }
} }
} }
@ -243,7 +245,7 @@ fn link(
fn target_triple(sess: &Session) -> target_lexicon::Triple { fn target_triple(sess: &Session) -> target_lexicon::Triple {
match sess.target.llvm_target.parse() { match sess.target.llvm_target.parse() {
Ok(triple) => triple, Ok(triple) => triple,
Err(err) => sess.fatal(format!("target not recognized: {}", err)), Err(err) => sess.dcx().fatal(format!("target not recognized: {}", err)),
} }
} }
@ -310,17 +312,18 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
Some(value) => { Some(value) => {
let mut builder = let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| { cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.fatal(format!("can't compile for {}: {}", target_triple, err)); sess.dcx().fatal(format!("can't compile for {}: {}", target_triple, err));
}); });
if let Err(_) = builder.enable(value) { if let Err(_) = builder.enable(value) {
sess.fatal("the specified target cpu isn't currently supported by Cranelift."); sess.dcx()
.fatal("the specified target cpu isn't currently supported by Cranelift.");
} }
builder builder
} }
None => { None => {
let mut builder = let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| { cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.fatal(format!("can't compile for {}: {}", target_triple, err)); sess.dcx().fatal(format!("can't compile for {}: {}", target_triple, err));
}); });
if target_triple.architecture == target_lexicon::Architecture::X86_64 { if target_triple.architecture == target_lexicon::Architecture::X86_64 {
// Don't use "haswell" as the default, as it implies `has_lzcnt`. // Don't use "haswell" as the default, as it implies `has_lzcnt`.
@ -333,7 +336,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
match isa_builder.finish(flags) { match isa_builder.finish(flags) {
Ok(target_isa) => target_isa, Ok(target_isa) => target_isa,
Err(err) => sess.fatal(format!("failed to build TargetIsa: {}", err)), Err(err) => sess.dcx().fatal(format!("failed to build TargetIsa: {}", err)),
} }
} }

View File

@ -74,7 +74,7 @@ fn create_entry_fn(
let cmain_func_id = match m.declare_function(entry_name, Linkage::Export, &cmain_sig) { let cmain_func_id = match m.declare_function(entry_name, Linkage::Export, &cmain_sig) {
Ok(func_id) => func_id, Ok(func_id) => func_id,
Err(err) => { Err(err) => {
tcx.sess tcx.dcx()
.fatal(format!("entry symbol `{entry_name}` declared multiple times: {err}")); .fatal(format!("entry symbol `{entry_name}` declared multiple times: {err}"));
} }
}; };
@ -171,7 +171,7 @@ fn create_entry_fn(
} }
if let Err(err) = m.define_function(cmain_func_id, &mut ctx) { if let Err(err) = m.define_function(cmain_func_id, &mut ctx) {
tcx.sess.fatal(format!("entry symbol `{entry_name}` defined multiple times: {err}")); tcx.dcx().fatal(format!("entry symbol `{entry_name}` defined multiple times: {err}"));
} }
unwind_context.add_function(cmain_func_id, &ctx, m.isa()); unwind_context.add_function(cmain_func_id, &ctx, m.isa());

View File

@ -397,7 +397,7 @@ pub(crate) fn new_stack_slot(
if layout.size.bytes() >= u64::from(u32::MAX - 16) { if layout.size.bytes() >= u64::from(u32::MAX - 16) {
fx.tcx fx.tcx
.sess .dcx()
.fatal(format!("values of type {} are too big to store on the stack", layout.ty)); .fatal(format!("values of type {} are too big to store on the stack", layout.ty));
} }